PHP2Py

Path: mv.asterisco.pt!mvalente
From: mvale…@ruido-visual.pt (Mario Valente)
Newsgroups: mv
Subject: PHP2Py
Date: Sun, 10 Jun 07 01:04:21 GMT

If I had the time and patience of days gone by, I would
get my photocopied Aho compiler book [1] from some closet or
box laying about (I dont know which), get my skills up on
XSLT (which I hate from back experience [2]) and use the
PHC [3] PHP compiler option of outputting AST trees [4]
in XML format to create PHP2PY, a PHP-to-Python translator,
using XSLT to transform the PHC-created AST XML tree
into Python source code.

[1]
http://en.wikipedia.org/wiki/Principles_of_Compiler_Design
http://en.wikipedia.org/wiki/Compilers:_Principles%2C_Techniques%2C_and_Tools

[2]
http://www.gildot.org/articles/04/05/21/1654202.shtml#10

[3]
http://www.phpcompiler.org/doc/runningphc.html#xml

[4]
http://en.wikipedia.org/wiki/Abstract_syntax_tree

As it is, downloading, installing and running PHC to
look at the generated XML for a simple “Hello World” and
putting together a proof-of-concept translator will have
to do to satisfy my hacking thirst…

— MV

PS – If you want to try it out, go get PHC, use it to
generate an XML AST of <? echo “Hello world!”; ?> into
a file called hello.xml. Processing it with the following
Python script should get you this:

#PHP2PY generated
print ‘Hello world!’

8<—————————————————<8
import xml.parsers.expat

InMethod=0
InString=0
MethodCall=0
StringValue=0

def start_element(name, attrs):
global InMethod, InString, MethodCall, StringValue

#print 'Start element:', name, attrs
if name == 'Token_method_name':
InMethod=1
if name == 'Token_string':
InString=1

if name == 'value' and InMethod:
MethodCall=1
if name == 'value' and InString:
StringValue=1

def end_element(name):
global InMethod, InString, MethodCall, StringValue

#print 'End element:', name
if name == 'Token_method_name':
InMethod=0
if name == 'Token_string':
InString=0

def char_data(data):
global InMethod, InString, MethodCall, StringValue

if MethodCall:
if data == "%run%": print "#PHP2PY generated"
if data == "echo": print "print",
MethodCall=0
if StringValue:
print "'"+data+"'"
StringValue=0

p = xml.parsers.expat.ParserCreate()

p.StartElementHandler = start_element
p.EndElementHandler = end_element
p.CharacterDataHandler = char_data

hellofile = open("hello.xml")
p.ParseFile(hellofile)
hellofile.close()

Comments are closed.