Generating C++ code
torriem at gmail.com
Wed Oct 10 16:15:16 CEST 2012
On 10/09/2012 10:00 AM, Jean-Michel Pichavant wrote:
> I'm trying to generate C++ code from an XML file. I'd like to use a template engine, which imo produce something readable and maintainable.
> My google search about this subject has been quite unsuccessful, I've been redirected to template engine specific to html mostly.
> Any advice would be appreciated.
There are two ways I can see to do this.
One is to use XSLT. XML is designed to be transformed easily, and XSLT
is the standard vehicle to do this transformation. You can use XSLT to
translate an XML document to HTML, for example, or to another schema of
XML, or to something non-XML like plain text, Tex, or even C++ code.
XSLT itself is turing complete, so complicated, logical transformations
are possible. Since I know of no existing transformation templates for
emitting C++, or any other language, you'll have to write it yourself.
Yes it won't be python code per se, though you can drive the XML XSLT
engine from python using a module called lxml. Anyway, XSLT is
complicated (I have done nothing in it myself), but it is designed for
this kind of thing.
Secondly, you could just use a python XML module of some kind, read the
document in, traverse the nodes and emit code. This is basic compiler
theory, though your source code is likely already in an abstract syntax
tree (XML). And I bet you could make it one pass, as you can rely on
the compiler to check symbol names for you. Compilers are not simple
beasts, but they are fun to write, and very educational. You get to
learn about grammars and recursive descent parsing (though the XML
library basically does both for you).
More information about the Python-list