program tip

다른 프로그래밍 언어로 쉽게 번역 할 수 있도록 코드에 어떤 종류의 패턴을 적용 할 수 있습니까?

radiobox 2020. 8. 27. 07:39
반응형

다른 프로그래밍 언어로 쉽게 번역 할 수 있도록 코드에 어떤 종류의 패턴을 적용 할 수 있습니까? [닫은]


나는 한 프로그래밍 언어에서 다른 프로그래밍 언어로 코드를 번역하는 것을 목표로하는 사이드 프로젝트를 시작하려고합니다. 제가 시작하는 언어는 PHP와 Python입니다 (Python에서 PHP로 시작하는 것이 더 쉬울 것입니다).하지만 이상적으로는 (상대적인) 쉽게 다른 언어를 추가 할 수 있습니다. 계획은 다음과 같습니다.

  • 이것은 웹 개발을위한 것입니다. 원본 코드와 대상 코드는 프레임 워크 위에 배치됩니다 (또한 작성해야 함). 이러한 프레임 워크는 MVC 디자인 패턴을 수용하고 엄격한 코딩 규칙을 따릅니다. 이렇게하면 번역이 다소 쉬워집니다.

  • 또한 IOC 및 종속성 주입을 검토하고 있습니다. 번역 프로세스를 더 쉽게 만들고 오류 발생 가능성을 줄일 수 있기 때문입니다.

  • 저는 추상 구문 트리를 조작 할 수있는 파이썬의 파서 모듈 을 사용할 것입니다 . 분명히 PHP로 얻을 수있는 가장 가까운 것은 token_get_all () 이며 시작입니다.

  • 그때부터 AST, 기호 테이블 및 제어 흐름을 구축 할 수 있습니다.

그러면 코드 출력을 시작할 수 있다고 믿습니다. 완벽한 번역이 필요하지 않습니다 . 여전히 생성 된 코드를 검토하고 문제를 해결해야합니다. 이상적으로 번역자는 문제가있는 번역에 플래그를 지정해야합니다.

"도대체이게 뭐야?"라고 묻기 전에 답은 ... 흥미로운 학습 경험이 될 것입니다. 이를 덜 어렵게 만드는 방법에 대한 통찰력이 있으면 알려주십시오.


편집하다:

번역을 수행하는 방법보다 코드를 더 쉽게 번역 (예 : IoC, SOA?) 할 수 있도록 코드에 어떤 종류의 패턴을 적용 할 수 있는지 알고 싶습니다.


저는 1995 년부터 강력한 컴퓨터 과학자 팀의 지원을 받아 범용 프로그램 조작 (언어 번역이 특별한 경우)을 수행하는 도구 (DMS 소프트웨어 리엔지니어링 툴킷)구축해 왔습니다 . DMS는 일반 구문 분석, AST 구축, 기호 테이블, 제어 및 데이터 흐름 분석, 번역 규칙 적용, 주석이있는 소스 텍스트 재생성 등을 제공하며, 모두 컴퓨터 언어의 명시 적 정의에 따라 매개 변수화됩니다.

이 작업을 수행하는 데 필요한 기계의 양은 방대하며 (특히 일반적인 방식으로 여러 언어에 대해이 작업을 수행하려는 경우) 신뢰할 수없는 정의를 가진 언어에 대해 신뢰할 수있는 파서가 필요합니다 (PHP는 이에 대한 완벽한 예입니다. ).

언어 대 언어 번역기를 만들거나 시도하는 것에 대해 생각하는 데 아무런 문제가 없지만 실제 언어에 대해서는 예상보다 훨씬 더 큰 작업이 될 것이라고 생각합니다. 우리는 단지 DMS에만 100 명의 인력을 투자했고 각각의 "신뢰할 수있는"언어 정의 (PHP 용으로 고통스럽게 구축 한 언어 포함)에 6-12 개월을 투자했습니다. C ++와 같은 불쾌한 언어의 경우 훨씬 더 많습니다. 그것은 "지옥의 학습 경험"이 될 것입니다. 우리를위한 것입니다. (위 웹 사이트의 기술 문서 섹션에서 학습을 바로 시작할 수 있습니다.)

사람들은 종종 익숙한 기술로 시작하여 일종의 일반화 된 기계를 만들려고 시도합니다. (Python AST가 좋은 예입니다). 좋은 소식은 작업의 일부가 완료되었다는 것입니다. 나쁜 소식은 기계에 엄청난 양의 가정이 내장되어 있다는 것입니다. 대부분은 다른 일을하도록 씨름하기 전까지는 발견 할 수 없습니다. 그 시점에서 당신은 기계가 원래하는 일을하도록 연결되어 있다는 것을 알게되며, 실제로 다른 일을하려는 당신의 시도에 저항 할 것입니다. (Python AST를 사용하여 PHP를 모델링하는 것이 재미있을 것 같습니다.)

제가 DMS를 구축하기 시작한 이유는 그러한 가정이 거의 내장되지 않은 기초를 구축하기 위해서였습니다. 우리에게 골칫거리가되는 것도 있습니다. 지금까지 블랙홀은 없습니다. (지난 15 년 동안 제 일에서 가장 힘든 부분은 그러한 가정이 들어오지 못하도록하는 것입니다.)

많은 사람들은 또한 그들이 구문 분석을 할 수 있다면 (그리고 아마도 AST를 얻을 수 있다면) 복잡한 일을 할 수 있다고 생각하는 실수를합니다. 어려운 교훈 중 하나는 좋은 프로그램 분석이나 변환을 수행하기 위해 기호 테이블과 흐름 분석이 필요하다는 것입니다. AST가 필요하지만 충분하지 않습니다. 이것이 Aho & Ullman의 컴파일러 책이 2 장에서 멈추지 않는 이유입니다. (OP는 AST를 넘어서 추가 기계를 구축 할 계획이라는 점에서이 권리가 있습니다). 이 주제에 대한 자세한 내용은 Life After Parsing을 참조하십시오 .

"완벽한 번역이 필요 없다"는 말은 번거 롭다. 약한 번역가가하는 일은 코드의 "쉬운"80 %를 변환하여 어려운 20 %는 손으로 할 수 있도록하는 것입니다. 변환하려는 응용 프로그램이 매우 작고 한 번만 잘 변환하려는 경우 20 %는 괜찮습니다. 많은 응용 프로그램 (또는 시간이 지남에 따라 약간 변경된 동일한 응용 프로그램)을 변환하려는 경우 좋지 않습니다. 100K SLOC를 변환하려고 시도하면 20 %는 번역, 이해 및 수정하기 어려운 원본 코드 20,000 줄이 이미 이해하지 못하는 번역 된 프로그램의 다른 80,000 줄의 맥락에서 수정됩니다. 엄청난 노력이 필요합니다. 백만 라인 수준에서 이것은 실제로 불가능합니다.더 어렵고 그들은 일반적으로 오랜 시간 지연, 높은 비용 및 종종 완전한 실패로 고통스럽게 발견합니다.)

대규모 시스템을 번역하기 위해 촬영해야하는 것은 90 %의 높은 전환율이거나 번역 활동의 수동 부분을 완료하지 못할 가능성이 높습니다.

또 다른 주요 고려 사항은 번역 할 코드의 크기입니다. 좋은 도구를 사용하더라도 작동하고 강력한 번역기를 만드는 데는 많은 에너지가 필요합니다. 단순히 수동 변환을 수행하는 대신 번역기를 구축하는 것이 섹시하고 멋져 보이지만, 소규모 코드베이스 (예 : 경험상 최대 약 100K SLOC)의 경우 경제적 측면에서이를 정당화하지 않습니다. 아무도이 답변을 좋아하지 않지만 실제로 10K SLOC 코드 만 번역해야한다면 총알을 깨물고 실행하는 것이 좋습니다. 그리고 네, 그것은 고통 스럽습니다.

저는 우리의 도구가 매우 훌륭하다고 생각합니다 (하지만 저는 꽤 편견이 있습니다). 그리고 좋은 번역가를 만드는 것은 여전히 ​​매우 어렵습니다. 약 1.5 ~ 2 인이 걸리며 도구 사용법을 알고 있습니다. 차이점은 이렇게 많은 기계를 사용하면 실패하는 것보다 훨씬 더 자주 성공 한다는 것입니다.


내 대답은 Ira가 그의 대답에서 잘 다룬 상위 수준이 아닌 다른 언어로 번역하기 위해 Python을 구문 분석하는 특정 작업을 다룰 것입니다.

간단히 말해서 파서 모듈을 사용하지 마십시오. 더 쉬운 방법이 있습니다.

astPython 2.6부터 사용할 수있는 모듈은 작업 할 준비된 AST를 제공하므로 필요에 훨씬 더 적합합니다. 작년 에이 기사를 작성 했지만 간단히 말해서 Python 소스 코드를 AST로 구문 분석 하는 parse방법을 사용합니다 ast. parser모듈은 당신에게 파스 트리가 아닌 AST를 제공 할 것입니다. 차이점에주의하십시오 .

이제 Python의 AST는 매우 상세하기 때문에 AST가 주어지면 프런트 엔드 작업이 그렇게 어렵지 않습니다. 기능의 일부에 대한 간단한 프로토 타입을 아주 빨리 준비 할 수 있다고 생각합니다. 그러나 완전한 솔루션을 얻으려면 주로 언어의 의미가 다르기 때문에 더 많은 시간이 걸립니다. 언어의 간단한 하위 집합 (함수, 기본 유형 등)은 쉽게 번역 할 수 있지만 더 복잡한 계층에 들어가면 한 언어의 핵심을 다른 언어로 에뮬레이트하기 위해 무거운 기계가 필요합니다. 예를 들어, PHP에 존재하지 않는 Python의 생성기와 목록 이해를 고려하십시오 (내가 아는 한, PHP가 관련되어있을 때 분명히 좋지 않음).

마지막 팁을 제공하기 위해 2to3Python 개발자가 Python 2 코드를 Python 3 코드로 변환하기 위해 만든 도구를 고려하십시오 . 프런트 엔드에는 Python을 무언가 로 번역하는 데 필요한 대부분의 요소가 있습니다 . 그러나 Python 2와 3의 코어가 비슷하기 때문에 에뮬레이션 기계가 필요하지 않습니다.


번역가를 쓰는 것은 불가능하지 않습니다. 특히 Joel의 인턴 이 여름에 한 것을 고려하면 더욱 그렇습니다 .

하나의 언어를하고 싶다면 쉽습니다. 더 많이하고 싶다면 조금 더 어렵지만 너무 많지는 않습니다. 가장 어려운 부분은 모든 튜링 완성 언어는 다른 튜링 완성 언어가하는 일을 할 수 있지만 내장 데이터 유형은 언어가 놀랍도록 변경 될 수 있다는 것입니다.

예를 들면 :

word = 'This is not a word'
print word[::-2]

소요 많이 (좋아, 잘가 여전히 반복 구조와 상당히 짧은 그것을 할 수 있지만) 복제하는 C ++ 코드를.

제 생각에는 약간 제쳐두고 요.

언어 문법을 기반으로 토크 나이저 / 파서를 작성한 적이 있습니까? 이 프로젝트의 주요 부분이기 때문에 그렇게하지 않았다면 그 방법을 배우고 싶을 것입니다. 내가 할 일은 기본적인 Turing 완전한 구문을 만드는 것 입니다. 파이썬 바이트 코드 와 상당히 비슷합니다 . 그런 다음 언어 문법 (아마도 BNF 사용 ) 을 취하고 문법을 기반으로 언어를 중간 언어로 컴파일 하는 어휘 분석기 / 파서를 만듭니다 . 그런 다음 당신이 원하는 것은 반대로-당신의 언어에서 문법을 기반으로 목표 언어로 파서를 생성하는 것입니다.

내가 본 가장 명백한 문제는 처음 에는 특히 Python과 같은 더 강력한 * 언어에서 끔찍하게 비효율적 인 코드를 만들 수 있다는 것입니다 .

그러나 이렇게하면 결과를 최적화하는 방법을 알아낼 수있을 것입니다. 요약:

  • 제공된 문법 읽기
  • 프로그램을 중간 (튜링 완료) 구문으로 컴파일
  • 중간 프로그램을 최종 언어로 컴파일 (제공된 문법에 따라)
  • ...?
  • 이익!(?)

* 강력하다는 것은 이것이 4 줄을 필요로한다는 것을 의미합니다.

myinput = raw_input("Enter something: ")
print myinput.replace('a', 'A')
print sum(ord(c) for c in myinput)
print myinput[::-1]

그런 일을 할 수있는 다른 언어를 4 줄로 보여 주시면 파이썬만큼 강력한 언어를 보여 드리겠습니다.


There are a couple answers telling you not to bother. Well, how helpful is that? You want to learn? You can learn. This is compilation. It just so happens that your target language isn't machine code, but another high-level language. This is done all the time.

There's a relatively easy way to get started. First, go get http://sourceforge.net/projects/lime-php/ (if you want to work in PHP) or some such and go through the example code. Next, you can write a lexical analyzer using a sequence of regular expressions and feed tokens to the parser you generate. Your semantic actions can either output code directly in another language or build up some data structure (think objects, man) that you can massage and traverse to generate output code.

You're lucky with PHP and Python because in many respects they are the same language as each other, but with different syntax. The hard part is getting over the semantic differences between the grammar forms and data structures. For example, Python has lists and dictionaries, while PHP only has assoc arrays.

The "learner" approach is to build something that works OK for a restricted subset of the language (such as only print statements, simple math, and variable assignment), and then progressively remove limitations. That's basically what the "big" guys in the field all did.

Oh, and since you don't have static types in Python, it might be best to write and rely on PHP functions like "python_add" which adds numbers, strings, or objects according to the way Python does it.

Obviously, this can get much bigger if you let it.


I will second @EliBendersky point of view regarding using ast.parse instead of parser (which I did not know about before). I also warmly recommend you to review his blog. I used ast.parse to do Python->JavaScript translator (@https://bitbucket.org/amirouche/pythonium). I've come up with Pythonium design by somewhat reviewing other implementations and trying them on my own. I forked Pythonium from https://github.com/PythonJS/PythonJS which I also started, It's actually a complete rewrite . The overall design is inspired from PyPy and http://www.hpl.hp.com/techreports/Compaq-DEC/WRL-89-1.pdf paper.

Everything I tried, from beginning to the best solution, even if it looks like Pythonium marketing it really isn't (don't hesitate to tell me if something doesn't seem correct to the netiquette):

  • Implement Python semantic in Plain Old JavaScript using prototype inheritance: AFAIK it's impossible to implement Python multiple inheritance using JS prototype object system. I did try to do it using other tricks later (cf. getattribute). As far as I know there is no implementation of Python multiple inheritance in JavaScript, the best that exists is Single inhertance + mixins and I'm not sure they handle diamond inheritance. Kind of similar to Skulpt but without google clojure.

  • I tried with Google clojure, just like Skulpt (compiler) instead of actually reading Skulpt code #fail. Anyway because of JS prototype based object system still impossible. Creating binding was very very difficult, you need to write JavaScript and a lot of boilerplate code (cf. https://github.com/skulpt/skulpt/issues/50 where I am the ghost). At that time there was no clear way to integrate the binding in the build system. I think that Skulpt is a library and you just have to include your .py files in the html to be executed, no compilation phase required to be done by the developer.

  • Tried pyjaco (compiler) but creating bindings (calling Javascript code from Python code) was very difficult, there was too much boilerplate code to create every time. Now I think pyjaco is the one that more near Pythonium. pyjaco is written in Python (ast.parse too) but a lot is written in JavaScript and it use prototype inheritance.

I never actually succeed at running Pyjamas #fail and never tried to read the code #fail again. But in my mind PyJamas was doing API->API tranlation (or framework to framework) and not Python to JavaScript translation. The JavaScript framework consume data that is already in the page or data from the server. Python code is only "plumbing". After that I discovered that pyjamas was actually a real python->js translator.

Still I think it's possible to do API->API (or framework->framework) translation and that's basicly what I do in Pythonium but at lower level. Probably Pyjamas use the same algorithm as Pythonium...

Then I discovered brython fully written in Javascript like Skulpt, no need for compilation and lot of fluff... but written in JavaScript.

Since the initial line written in the course of this project, I knew about PyPy, even the JavaScript backend for PyPy. Yep, you can, if you find it, directly generate a Python interpreter in JavaScript from PyPy. People say, it was a disaster. I read no where why. But I think the reason is that the intermediate language they use to implement the interpreter, RPython, is a subset of Python tailored to be translated to C (and maybe asm). Ira Baxter says you always make assumptions when you build something and probably you fine tune it to be the best at what it's meant to do in the case of PyPy: Python->C translation. Those assumptions might not be relevant in another context worse they can infere overhead otherwise said direct translation will most likely always be better.

Having the interpreter written in Python sounded like a (very) good idea. But I was more interested in a compiler for performance reasons also it's actually more easy to compile Python to JavaScript than interpret it.

I started PythonJS with the idea of putting together a subset of Python that I could easily translate to JavaScript. At first I didn't even bother to implement OO system because of past experience. The subset of Python that I achieved to translate to JavaScript are:

  • function with full parameters semantic both in definition and calling. This is the part I am most proud of.
  • while/if/elif/else
  • Python types were converted to JavaScript types (there is no python types of any kind)
  • for could iterate over Javascript arrays only (for a in array)
  • Transparent access to JavaScript: if you write Array in the Python code it will be translated to Array in javascript. This is the biggest achievement in terms of usability over its competitors.
  • You can pass function defined in Python source to javascript functions. Default arguments will be taken into account.
  • It add has special function called new which is translated to JavaScript new e.g: new(Python)(1, 2, spam, "egg") is translated to "new Python(1, 2, spam, "egg").
  • "var" are automatically handled by the translator. (very nice finding from Brett (PythonJS contributor).
  • global keyword
  • closures
  • lambdas
  • list comprehensions
  • imports are supported via requirejs
  • single class inheritance + mixin via classyjs

This seems like a lot but actually very narrow compared to full blown semantic of Python. It's really JavaScript with a Python syntax.

The generated JS is perfect ie. there is no overhead, it can not be improved in terms of performance by further editing it. If you can improve the generated code, you can do it from the Python source file too. Also, the compiler did not rely on any JS tricks that you can find in .js written by http://superherojs.com/, so it's very readable.

The direct descendant of this part of PythonJS is the Pythonium Veloce mode. The full implementation can be found @ https://bitbucket.org/amirouche/pythonium/src/33898da731ee2d768ced392f1c369afd746c25d7/pythonium/veloce/veloce.py?at=master 793 SLOC + around 100 SLOC of shared code with the other translator.

An adapted version of pystones.py can be translated in Veloce mode cf. https://bitbucket.org/amirouche/pythonium/src/33898da731ee2d768ced392f1c369afd746c25d7/pystone/?at=master

After having setup basic Python->JavaScript translation I choosed another path to translate full Python to JavaScript. The way of glib doing object oriented class based code except the target language is JS so you have access to arrays, map-like objects and many other tricks and all that part was written in Python. IIRC there is no javascript code written by in Pythonium translator. Getting single inheritance is not difficult here are the difficult parts making Pythonium fully compliant with Python:

  • spam.egg in Python is always translated to getattribute(spam, "egg") I did not profile this in particular but I think that where it loose a lot of time and I'm not sure I can improve upon it with asm.js or anything else.
  • method resolution order: even with the algorithm written in Python, translating it to Python Veloce compatible code was a big endeavour.
  • getattributre: the actual getattribute resolution algorithm is kind of tricky and it still doesn't support data descriptors
  • metaclass class based: I know where to plug the code, but still...
  • last bu not least: some_callable(...) is always transalted to "call(some_callable)". AFAIK the translator doesn't use inference at all, so every time you do a call you need to check which kind of object it is to call it they way it's meant to be called.

This part is factored in https://bitbucket.org/amirouche/pythonium/src/33898da731ee2d768ced392f1c369afd746c25d7/pythonium/compliant/runtime.py?at=master It's written in Python compatible with Python Veloce.

The actual compliant translator https://bitbucket.org/amirouche/pythonium/src/33898da731ee2d768ced392f1c369afd746c25d7/pythonium/compliant/compliant.py?at=master doesn't generate JavaScript code directly and most importantly doesn't do ast->ast transformation. I tried the ast->ast thing and ast even if nicer than cst is not nice to work with even with ast.NodeTransformer and more importantly I don't need to do ast->ast.

Doing python ast to python ast in my case at least would maybe be a performance improvement since I sometime inspect the content of a block before generating the code associated with it, for instance:

  • var/global: to be able to var something I must know what I need to and not to var. Instead of generating a block tracking which variable are created in a given block and inserting it on top of the generated function block I just look for revelant variable assignation when I enter the block before actually visiting the child node to generate the associated code.
  • yield, generators have, as of yet, a special syntax in JS, so I need to know which Python function is a generator when I want to write the "var my_generator = function"

So I don't really visit each node once for each phase of the translation.

The overall process can be described as:

Python source code -> Python ast -> Python source code compatible with Veloce mode -> Python ast -> JavaScript source code

Python builtins are written in Python code (!), IIRC there is a few restrictions related to bootstraping types, but you have access to everything that can translate Pythonium in compliant mode. Have a look at https://bitbucket.org/amirouche/pythonium/src/33898da731ee2d768ced392f1c369afd746c25d7/pythonium/compliant/builtins/?at=master

Reading JS code generated from pythonium compliant can be understood but source maps will greatly help.

The valuable advice I can give you in the light of this experience are kind old farts:

  • extensively review the subject both in literature and existing projects closed source or free. When I reviewed the different existing projects I should have given it way more time and motivation.
  • ask questions! If I knew beforehand that PyPy backend was useless because of the overhead due to C/Javascript semantic mismatch. I would maybe had Pythonium idea way before 6 month ago maybe 3 years ago.
  • know what you want to do, have a target. For this project I had different objectives: pratice a bit a javascript, learn more of Python and be able to write Python code that would run in the browser (more and that below).
  • failure is experience
  • a small step is a step
  • start small
  • dream big
  • do demos
  • iterate

With Python Veloce mode only, I'm very happy! But along the way I discovered that what I was really looking for was liberating me and others from Javascript but more importantly being able to create in a comfortable way. This lead me to Scheme, DSL, Models and eventually domain specific models (cf. http://dsmforum.org/).

About what Ira Baxter response:

The estimations are not helpful at all. I took me more or less 6 month of free time for both PythonJS and Pythonium. So I can expect more from full time 6 month. I think we all know what 100 man-year in an enterprise context can mean and not mean at all...

When someone says something is hard or more often impossible, I answer that "it only takes time to find a solution for a problem that is impossible" otherwise said nothing is impossible except if it's proven impossible in this case a math proof...

If it's not proven impossible then it leaves room for imagination:

  • finding a proof proving it's impossible

and

  • If it is impossible there may be an "inferior" problem that can have a solution.

or

  • if it's not impossible, finding a solution

It's not just optimistic thinking. When I started Python->Javascript everybody was saying it was impossible. PyPy impossible. Metaclasses too hard. etc... I think that the only revolution that brings PyPy over Scheme->C paper (which is 25 years old) is some automatic JIT generation (based hints written in the RPython interpreter I think).

Most people that say that a thing is "hard" or "impossible" don't provide the reasons. C++ is hard to parse? I know that, still they are (free) C++ parser. Evil is in the detail? I know that. Saying it's impossible alone is not helpful, It's even worse than "not helpful" it's discouraging, and some people mean to discourage others. I heard about this question via https://stackoverflow.com/questions/22621164/how-to-automatically-generate-a-parser-code-to-code-translator-from-a-corpus.

What would be perfection for you? That's how you define next goal and maybe reach the overall goal.

I am more interested in knowing what kinds of patterns I could enforce on the code to make it easier to translate (ie: IoC, SOA ?) the code than how to do the translation.

I see no patterns that can not be translated from one language to another language at least in a less than perfect way. Since language to language translation is possible, you'd better aim for this first. Since, I think according to http://en.wikipedia.org/wiki/Graph_isomorphism_problem, translation between two computer languages is a tree or DAG isomorphism. Even if we already know that they are both turing complete, so...

Framework->Framework which I better visualize as API->API translation might still be something that you might keep in mind as a way to improve the generated code. E.g: Prolog as very specific syntax but still you can do Prolog like computation by describing the same graph in Python... If I was to implement a Prolog to Python translator I wouldn't implement unification in Python but in a C library and come up with a "Python syntax" that is very readable for a Pythonist. In the end, syntax is only "painting" for which we give a meaning (that's why I started scheme). Evil is in the detail of the language and I'm not talking about the syntax. The concepts that are used in the language getattribute hook (you can live without it) but required VM features like tail-recursion optimisation can be difficult to deal with. You don't care if the initial program doesn't use tail recursion and even if there is no tail recursion in the target language you can emulate it using greenlets/event loop.

For target and source languages, look for:

  • Big and specific ideas
  • Tiny and common shared ideas

From this will emerge:

  • Things that are easy to translate
  • Things that are difficult to translate

You will also probably be able to know what will be translated to fast and slow code.

There is also the question of the stdlib or any library but there is no clear answer, it depends of your goals.

Idiomatic code or readable generated code have also solutions...

Targeting a platform like PHP is much more easy than targeting browsers since you can provide C-implementation of slow and/or critical path.

Given you first project is translating Python to PHP, at least for the PHP3 subset I know of, customising veloce.py is your best bet. If you can implement veloce.py for PHP then probably you will be able to run the compliant mode... Also if you can translate PHP to the subset of PHP you can generate with php_veloce.py it means that you can translate PHP to the subset of Python that veloce.py can consume which would mean that you can translate PHP to Javascript. Just saying...

You can also have a look at those libraries:

Also you might be interested by this blog post (and comments): https://www.rfk.id.au/blog/entry/pypy-js-poc-jit/


You could take a look at the Vala compiler, which translates Vala (a C#-like language) into C.

참고URL : https://stackoverflow.com/questions/3455456/what-kinds-of-patterns-could-i-enforce-on-the-code-to-make-it-easier-to-translat

반응형