Coder Social home page Coder Social logo

ts2php's Introduction

ts2php

under development

TypeScript 转 PHP

A Compiler which can compile TypeScript to PHP.

Language Build Status npm package npm downloads semantic-release

Usage

compiler

import {compile} from 'ts2php';

const result = compile(filePath, options);

runtime

部分功能依赖一个 PHP 的类库,需要在 PHP 工程中引入

Some features are implemented by a PHP helper class, which need to be included in your PHP code.

require_once("/path/to/ts2php/dist/runtime/Ts2Php_Helper.php");

CLI

Quick Start:

$ npm i -g ts2php
$ ts2php ./a.ts                   # 编译输出到 stdout

使用配置并输出到文件:

$ cat config.js
module.exports = {
  emitHeader: false
};
$ ts2php -c config.js src/ -o output/

更多选项:

$ ts2php --show-diagnostics       # 输出诊断信息
$ ts2php --emit-header            # 输出头部信息
$ ts2php -h                       # 更多功能请查看帮助

update ts2php version

Same TS code with different version of ts2php may result to different PHP code. When updating the version of ts2php, we should check the result PHP code manually. To simplify this process, we recommend to use ts2php-diff-checker. Specify two version of ts2php, and some source TS code, ts2php-diff-checker will generate diff info directly.

ts2php-check <pattern> <old-version> <new-version> [destination]

Features

Javascript Syntax

For more, see feature test markdowns: Javascript Syntax

Core JavaScript API

  • parseInt 只接收一个参数
  • parseFloat
  • encodeURIComponent
  • decodeURIComponent
  • encodeURI
  • __dirname
  • __filename
  • Date
    • Date.now
    • Date.prototype.getTime
    • Date.prototype.getDate
    • Date.prototype.getDay
    • Date.prototype.getFullYear
    • Date.prototype.getHours
    • Date.prototype.getMinutes
    • Date.prototype.getMonth
    • Date.prototype.getSeconds
    • Date.prototype.setDate
    • Date.prototype.setFullYear
    • Date.prototype.setHours
    • Date.prototype.setMinutes
    • Date.prototype.setMonth
    • Date.prototype.setSeconds
    • Date.prototype.setTime
  • Object
    • Object.assign
    • Object.keys
    • Object.values
    • Object.freeze
    • Object.prototype.hasOwnProperty
  • JSON
    • JSON.stringify 只接收一个参数
    • JSON.parse 只接收一个参数
  • console
    • console.log
    • console.info 转成 var_dump
    • console.error
  • String
    • String.prototype.replace 第二个参数只支持 string,不支持 Function
    • String.prototype.trim
    • String.prototype.trimRight
    • String.prototype.trimLeft
    • String.prototype.toUpperCase
    • String.prototype.toLowerCase
    • String.prototype.split
    • String.prototype.indexOf
    • String.prototype.substring
    • String.prototype.repeat
    • String.prototype.startsWidth
    • String.prototype.endsWidth
    • String.prototype.includes
    • String.prototype.padStart
    • String.prototype.match 只支持正则和字符串匹配
  • Array
    • Array.isArray
    • Array.prototype.length
    • Array.prototype.filter 回调函数只接收第一个参数
    • Array.prototype.push
    • Array.prototype.pop
    • Array.prototype.shift
    • Array.prototype.unshift
    • Array.prototype.concat
    • Array.prototype.reverse
    • Array.prototype.splice
    • Array.prototype.reverse
    • Array.prototype.map
    • Array.prototype.forEach
    • Array.prototype.indexOf
    • Array.prototype.join
    • Array.prototype.some
    • Array.prototype.every
    • Array.prototype.find
    • Array.prototype.findIndex
    • Array.prototype.sort
  • Number
    • Number.isInterger
    • Number.prototype.toFixed
    • Number.prototype.toString
  • Math
    • Math.abs
    • Math.acos
    • Math.acosh
    • Math.asin
    • Math.asinh
    • Math.atan
    • Math.atanh
    • Math.atan2
    • Math.cbrt
    • Math.ceil
    • Math.clz32
    • Math.cos
    • Math.cosh
    • Math.exp
    • Math.expm1
    • Math.floor
    • Math.hypot
    • Math.log
    • Math.log1p
    • Math.log10
    • Math.max
    • Math.min
    • Math.pow
    • Math.random
    • Math.round
    • Math.sin
    • Math.sinh
    • Math.sqrt
    • Math.tan
    • Math.tanh

Thanks to

Based on Typescript compiler

ts2php's People

Contributors

cxtom avatar dependabot[bot] avatar harttle avatar l5oo00 avatar meixg avatar orta avatar semantic-release-bot avatar wuyan1900 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ts2php's Issues

\Ts2phpHelper 支持不在根命名空间

目前它强制在根命名空间下,输出代码为 \Ts2phpHelper。是否可以把它改为 Ts2phpHelper,import 路径让使用方去 use?或者是否能提供个配置?感觉前者更合理一些。

spread 运算符支持在参数列表中展开

const prices = [6750, 6950, 6850, 6498, 7498, 6498, 6298, 5998, 6288, 6150, 6099, 5888];

// 最高价格
const maxPrice = Math.max(...prices);

// 最低价格
const minPrice = Math.min(...prices);

console.dir(maxPrice);
console.dir(minPrice);

unicode

$ node
> "x你好啊"[0]
'x'
> "x你好啊"[1]
'你'
$ php -a
Interactive shell

php > echo "x你好啊"[0];
x
php > echo "x你好啊"[1];
�

現在的翻譯不支持unicode

shorthand property assigment initializer 如果是import 进来的函数,无法正确添加 namespace。

如下代码:

import {aaa} from './aaa'; // namespace: \someModule\
let a = {
    aaa: aaa
};

现在可以正确翻译成:

require_once(dirname(__FILE__) . '/' . "./aaa.php");
$a = array(
    "aaa" => "\someModule\aaa"
);

但是如果使用简写形式:

import {aaa} from './aaa'; // namespace: \someModule\
let a = {
    aaa
};

从 ShorthandPropertyAssignment.name 中不能查找到 import 部分,无法添加上 namespace。

require_once(dirname(__FILE__) . '/' . "./aaa.php");
$a = array(
    "aaa" => ""aaa""
);

支持 export ... from

代码中的 export ... from 语法会被编译成空。例如:

index.ts:

export { foo } from './foo'

foo.ts:

export const foo = ''

ts2php index.ts 2>/dev/null输出为:

<?php
namespace 2d207422;

期望:

<?php
namespace 2d207422;
require_once('./foo.php')

麻烦的地方在于 export { a as b} from 的情况

函数中引用传参

TS 中函数的参数默认为引用传递:

let a = [];
function aaa(b) {
    b[0] = 1;
}
aaa(a);
console.log(a[0]); // 1

但 PHP 中默认为值传递:

$a = array();
function aaa($b) {
    $b['0'] = 1;
}
aaa($a);
echo $a['0']; // undefined

如果在转换函数定义时,参数部分增加 &,可以解决上述问题。

$a = array();
function aaa(&$b) {
    $b['0'] = 1;
}
aaa($a);
echo $a['0']; // 1

但函数参数为字面量形式时会报错,目前找到好的解决方法:

function aaa(&$b) {
    $b['0'] = 1;
}
aaa(array()); // Error

此外,如果函数返回值也会有引用传递问题,例如:

let a = [];
function bbb(c) {
    return c;
}
let b = bbb(a);
b[0] = 1;
console.log(a[0]); // 1

需要翻译成如下 PHP 代码才能有同样效果:

$a = array();
function &bbb(&$c) {
    return $c;
}
$b = &bbb($a);
$b["0"] = 1;

echo $a["0"];

问题更加复杂了

全局變量

全局變量不能正常工作。
需要global $...

Array.prototype.push不支持多参数

Array.prototype.push 传入多参数时,只会将第一个参数推入数组。

const test = [];
test.push(1, 2, 3);
test.push(3, 2, 3);
console.dir(test);    // output: [1, 3]

abstract 关键字输出

现存问题是:

  • abstract method 没有输出 abstract
  • abstract class 没有输出 abstract

第一点的必要性是,提供方法声明,在子类中实现。第二点的必要性是,abstract class 才能有 abstract method

默认移除类型的 import

import 会被翻译成 require_once,但是在 TypeScript 中会有一些 import 只是为了类型信息的。因为翻译后代码中没有引用,所以可以默认不产出这些 require_once。

(xs) => xs

function list_to_jsArray<T>(
    xs: LangVal,
    k_done: (p0: Array<LangVal>) => T,
    k_tail: (p0: Array<LangVal>, p1: LangVal) => T): T {
    let ret: Array<LangVal> = []
    while (construction_p(xs)) {
        ret.push(construction_head(xs))
        xs = construction_tail(xs)
    }
    if (null_p(xs)) {
        return k_done(ret)
    }
    return k_tail(ret, xs)
}

function maybe_list_to_jsArray(xs: LangVal): false | Array<LangVal> {
    return list_to_jsArray<false | Array<LangVal>>(xs, (xs) => xs, (xs, x) => false)
}

result

function list_to_jsArray($xs, &$k_done, &$k_tail) { // PHP Fatal error:  Only variables can be passed by reference
    $ret = array();
    while (construction_p($xs)) {
        array_push($ret, construction_head($xs));
        $xs = construction_tail($xs);
    }
    if (null_p($xs)) {
        return k_done($ret);
    }
    return k_tail($ret, $xs);
}
function maybe_list_to_jsArray($xs) {
    return list_to_jsArray($xs, function ($xs){
    return xs; // 應該是$xs
    }, function ($xs, $x){
    return false;
    });
}

bug?

https://gitlab.com/the-language/the-language/blob/99781459d3b5354ee70ed55d1f4fb83a999db336/core/pure/typescript/lang.ts

可以用tsc或typescript-to-lua編譯。

$ npx ts2php lang.ts 
[compile] lang.ts...
lang.ts:2071:5 - error TS2322: Type 'T | Trampoline<T>' is not assignable to type 'T'.
  Type 'Trampoline<T>' is not assignable to type 'T'.

2071     return i[1]
         ~~~~~~~~~~~

[error] Type 'T | Trampoline<T>' is not assignable to type 'T'. in /home/zaoqi/src/the-language/core/pure/php/lang.ts at 76632

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


No npm token specified.

An npm token must be created and set in the NPM_TOKEN environment variable on your CI environment.

Please make sure to create an npm token and to set it in the NPM_TOKEN environment variable on your CI environment. The token must allow to publish to the registry https://registry.npmjs.org/.


Good luck with your project ✨

Your semantic-release bot 📦🚀

array被複製。

a.ts

const a:Array<number>=[];
const b=a;
b[1]=0;
$ npx ts2php a.ts
[compile] a.ts...
<?php
namespace Eekyl;
$a = array();
$b = $a;
$b[1] = 0;
$ php -a
Interactive shell

php > <?php
php > namespace Eekyl;
PHP Parse error:  syntax error, unexpected '<', expecting end of file in php shell code on line 1
php > $a = array();
php > $b = $a;
php > $b[1] = 0;
php > var_dump($a);
array(0) {
}
php > 

function : PHP Fatal error: Only variables can be passed by reference

PHP Fatal error:  Only variables can be passed by reference in /home/zaoqi/the-language/core/pure/php/lang.php on line 283

https://gitlab.com/the-language/the-language/blob/0cf321e1d779e37a602bee2417d2d302ce6d47ad/core/pure/typescript/lang.ts
结果

function list_to_jsArray($xs, &$k_done, &$k_tail) {     $ret = array();     while (construction_p($xs)) {         array_push($ret, construction_head($xs));         $xs = construction_tail($xs);     }     if (null_p($xs)) {         return k_done($ret);     }     return k_tail($ret, $xs); } function maybe_list_to_jsArray($xs) {     return list_to_jsArray($xs, function ($xs){     return $xs;     }, function ($xs, $x){     return false;     }); }

函数编译之后成为变量了

在ts中import一个函数,并调用。经过ts2php编译后,输出为一个同名变量。
例如:

import { funcName } from 'filter'; 
export default class com extends Component {
    static filters = {
        funcName // 是一个函数
    }
}

经过ts2php编译之后,输出为:

require_once("@baidu/wise_filter");
class com extends Component {}
com::$filters = array(
    "funcName" => $funcName
);

支持命令行调用

import {compile} from 'ts2php';

const result = compile(filePath, options);

這樣不太方便。可增加一個命令。

__dirname 和 __filename 输出

应该输出为 __DIR____FILE__。一些观察到的点供参考:

  • php < 5.3 不支持 __DIR__,需要 dirname(__FILE__)
  • hhvm 中支持 __DIR__

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.