Translating code from Python to Smalltalk

110 views
Skip to first unread message

Giordano Bruno

unread,
Apr 24, 2012, 7:41:28 AM4/24/12
to ply-...@googlegroups.com
Friends,
I've been redirected from StackOverflow (http://stackoverflow.com/questions/10273513/translating-code-from-python-to-smalltalk) to here, may be you have better idea where to start. I want to do some automatic code translation from Python to Smalltalk because I've noticed some very simple sentences can be automatically translated. My guess is that sooner or later a mapping dictionary of rules is needed, but my interest is to have a very simple prototype working, like a code template from where to start working on, my experience in Python is limited so I will very appreciate any links or code you may provide. Here are some translation examples:

Assigning a variable to a value

Python

i = 1

Smalltalk

i := 1.

Creating a new instance of a class

Python

instance = module.ClassName()


Smalltalk

instance := ClassName new.


A for loop

Python

for a in [0,1,2]:
 
print (str(a)+str(a))


Smalltalk

#(0 1 2) do: [: a | Transcript show: a + a; cr ].

Any links or code template for doing simple translation from Python to Smalltalk (or other programming language for the case).
Cheers,

Giordano


Andrew Dalke

unread,
May 1, 2012, 4:27:02 AM5/1/12
to ply-...@googlegroups.com
On Apr 24, 2012, at 1:41 PM, Giordano Bruno wrote:
> Any links or code template for doing simple translation from Python to Smalltalk (or other programming language for the case).

Jython converts Python to Java byte code, and Iron Python does the same for the .Net environment.

PyPy converts Python to multiple back ends. For example, it has Javascript as a proof-of-concept back end.

Cython takes a Python-like language and generate C code which uses the Python runtime, and Nuitka is a different approach.

HOWEVER! Those handle the deep semantics, like operator overloading and metaclasses. If you want simple syntactic translation then you can do that with Python's 'ast' module. Here's how to get the AST:



>>> import ast
>>> compile("for x in [1,2,3]: print x", "<string>", "exec", ast.PyCF_ONLY_AST)
<_ast.Module object at 0x10c6308d0>
>>> module = compile("for x in [1,2,3]: print x", "<string>", "exec", ast.PyCF_ONLY_AST)
>>> ast.dump(module)
"Module(body=[For(target=Name(id='x', ctx=Store()), iter=List(elts=[Num(n=1), Num(n=2), Num(n=3)], ctx=Load()), body=[Print(dest=None, values=[Name(id='x', ctx=Load())], nl=True)], orelse=[])])"
>>>

With some tree walking you can get the basics of what you want pretty quickly. Since you're probably a Smalltalk fan, you could even dump the AST into text format, read it into a Smalltalk data structure, and let Smalltalk do the translation/evaluation.



Andrew
da...@dalkescientific.com


Reply all
Reply to author
Forward
0 new messages