views:

256

answers:

3

Suppose I wrote a compiler in Python or Ruby that translates a language into a C# AST.

How do I pretty-print this AST from Python or Ruby to get nicely indented C# code?

Thanks, Joel
+1  A: 

In python the pprint module is available.

Depending on how your data is structured it may not return the result your looking for.

monkut
A: 

One way would be to just print it and then invoke a code formatter.

Shane C. Mason
+1  A: 

Once you have an AST, this should be very easy. When you walk your AST, all you have to do is keep track of what your current indent level is -- you could use a global for this. The code that's walking the tree simply needs to increment the indent level every time you enter a block, and decrement it when you exit a block. Then, whenever you print a line of code, you call it like this:

print "\t"*indentlevel + code

You should end up with nicely formatted code. However, I'm a bit confused that you're asking this question -- if you have the skills to parse C# into an AST, I can't imagine you wouldn't be able to write a pretty-printing output function. :-)

Benson