1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/viewer.py Tue Oct 03 00:50:03 2006 +0200
1.3 @@ -0,0 +1,77 @@
1.4 +#!/usr/bin/env python
1.5 +
1.6 +"""
1.7 +View annotated sources.
1.8 +
1.9 +Copyright (C) 2006 Paul Boddie <paul@boddie.org.uk>
1.10 +
1.11 +This software is free software; you can redistribute it and/or
1.12 +modify it under the terms of the GNU General Public License as
1.13 +published by the Free Software Foundation; either version 2 of
1.14 +the License, or (at your option) any later version.
1.15 +
1.16 +This software is distributed in the hope that it will be useful,
1.17 +but WITHOUT ANY WARRANTY; without even the implied warranty of
1.18 +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1.19 +GNU General Public License for more details.
1.20 +
1.21 +You should have received a copy of the GNU General Public
1.22 +License along with this library; see the file LICENCE.txt
1.23 +If not, write to the Free Software Foundation, Inc.,
1.24 +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
1.25 +"""
1.26 +
1.27 +from compiler.visitor import ASTVisitor
1.28 +import sys
1.29 +
1.30 +class Viewer(ASTVisitor):
1.31 +
1.32 + """
1.33 + A viewing visitor for AST nodes.
1.34 + """
1.35 +
1.36 + def __init__(self, stream):
1.37 + ASTVisitor.__init__(self)
1.38 + self.cached_files = {}
1.39 + self.printed_lines = {}
1.40 + self.visitor = self
1.41 + self.stream = stream
1.42 +
1.43 + def process(self, module):
1.44 + self.dispatch(module)
1.45 +
1.46 + def dispatch(self, node):
1.47 + self.print_line(getattr(node, "filename", None), getattr(node, "lineno", None))
1.48 + ASTVisitor.dispatch(self, node)
1.49 +
1.50 + def print_line(self, filename, lineno):
1.51 + last_printed = self.printed_lines.get(filename, 0)
1.52 + if lineno > last_printed:
1.53 + self.stream.write(self.get_line(filename, lineno))
1.54 + self.printed_lines[filename] = lineno
1.55 +
1.56 + def get_line(self, filename, lineno):
1.57 + if filename is None or lineno is None:
1.58 + return ""
1.59 +
1.60 + if self.cached_files.has_key(filename):
1.61 + lines = self.cached_files[filename]
1.62 + else:
1.63 + f = open(filename)
1.64 + try:
1.65 + self.cached_files[filename] = lines = f.readlines()
1.66 + finally:
1.67 + f.close()
1.68 +
1.69 + try:
1.70 + return lines[lineno - 1]
1.71 + except IndexError:
1.72 + return ""
1.73 +
1.74 +# Convenience functions.
1.75 +
1.76 +def view(module, stream=None):
1.77 + viewer = Viewer(stream or sys.stdout)
1.78 + viewer.process(module.original)
1.79 +
1.80 +# vim: tabstop=4 expandtab shiftwidth=4