从 Python 漂亮打印 C#
假设我用 Python 或 Ruby 编写了一个编译器,将一种语言转换为 C# AST。
如何从 Python 或 Ruby 漂亮地打印这个 AST 以获得良好缩进的 C# 代码?
Thanks, Joel
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 python 中,pprint 模块可用。
根据您的数据结构,它可能不会返回您正在寻找的结果。
In python the pprint module is available.
Depending on how your data is structured it may not return the result your looking for.
一旦你有了 AST,这应该很容易。 当您遍历 AST 时,您所要做的就是跟踪当前的缩进级别 - 您可以为此使用全局。 遍历树的代码只需要在每次进入块时增加缩进级别,并在退出块时减少缩进级别。 然后,每当您打印一行代码时,您都可以这样调用它:
您最终应该得到格式良好的代码。 然而,我对你问这个问题感到有点困惑——如果你有能力将 C# 解析为 AST,我无法想象你无法编写一个漂亮的打印输出函数。 :-)
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:
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. :-)
一种方法是仅打印它,然后调用代码格式化程序。
One way would be to just print it and then invoke a code formatter.