Print AST nodes.
| 25 | |
| 26 | |
| 27 | class PrettyPrinter(gast.NodeVisitor): |
| 28 | """Print AST nodes.""" |
| 29 | |
| 30 | def __init__(self, color, noanno): |
| 31 | self.indent_lvl = 0 |
| 32 | self.result = '' |
| 33 | self.color = color |
| 34 | self.noanno = noanno |
| 35 | |
| 36 | def _color(self, string, color, attrs=None): |
| 37 | if self.color: |
| 38 | return termcolor.colored(string, color, attrs=attrs) |
| 39 | return string |
| 40 | |
| 41 | def _type(self, node): |
| 42 | return self._color(node.__class__.__name__, None, ['bold']) |
| 43 | |
| 44 | def _field(self, name): |
| 45 | return self._color(name, 'blue') |
| 46 | |
| 47 | def _value(self, name): |
| 48 | return self._color(name, 'magenta') |
| 49 | |
| 50 | def _warning(self, name): |
| 51 | return self._color(name, 'red') |
| 52 | |
| 53 | def _indent(self): |
| 54 | return self._color('| ' * self.indent_lvl, None, ['dark']) |
| 55 | |
| 56 | def _print(self, s): |
| 57 | self.result += s |
| 58 | self.result += '\n' |
| 59 | |
| 60 | def generic_visit(self, node, name=None): |
| 61 | # In very rare instances, a list can contain something other than a Node. |
| 62 | # e.g. Global contains a list of strings. |
| 63 | if isinstance(node, str): |
| 64 | if name: |
| 65 | self._print('%s%s="%s"' % (self._indent(), name, node)) |
| 66 | else: |
| 67 | self._print('%s"%s"' % (self._indent(), node)) |
| 68 | return |
| 69 | |
| 70 | if node._fields: |
| 71 | cont = ':' |
| 72 | else: |
| 73 | cont = '()' |
| 74 | |
| 75 | if name: |
| 76 | self._print('%s%s=%s%s' % (self._indent(), self._field(name), |
| 77 | self._type(node), cont)) |
| 78 | else: |
| 79 | self._print('%s%s%s' % (self._indent(), self._type(node), cont)) |
| 80 | |
| 81 | self.indent_lvl += 1 |
| 82 | for f in node._fields: |
| 83 | if self.noanno and f.startswith('__'): |
| 84 | continue |