~ubuntu-branches/ubuntu/karmic/pypy/karmic

« back to all changes in this revision

Viewing changes to pypy/module/recparser/hooksamples/tracer.py

  • Committer: Bazaar Package Importer
  • Author(s): Alexandre Fayolle
  • Date: 2007-04-13 09:33:09 UTC
  • Revision ID: james.westby@ubuntu.com-20070413093309-yoojh4jcoocu2krz
Tags: upstream-1.0.0
ImportĀ upstreamĀ versionĀ 1.0.0

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
"""this one logs simple assignments and somewhat clearly shows
 
2
that we need a nice API to define "joinpoints". Maybe a SAX-like
 
3
(i.e. event-based) API ?
 
4
 
 
5
XXX: crashes on everything else than simple assignment (AssAttr, etc.)
 
6
"""
 
7
 
 
8
from parser import ASTPrintnl, ASTConst, ASTName, ASTAssign, ASTMutator
 
9
from parser import install_compiler_hook, source2ast
 
10
 
 
11
BEFORE_LOG_SOURCE = """if '%s' in locals() or '%s' in globals():
 
12
    print '(before) %s <--', locals().get('%s', globals().get('%s', '<XXX>'))
 
13
"""
 
14
AFTER_LOG_SOURCE = "print '(after) %s <--', %s"
 
15
 
 
16
def get_statements(source):
 
17
    module = source2ast(source)
 
18
    return module.node.nodes
 
19
 
 
20
class Tracer(ASTMutator):
 
21
    def visitAssName(self, assname):
 
22
        assign = assname
 
23
        while not isinstance(assign, ASTAssign):
 
24
            assign = assign.parent
 
25
        stmt = assign.parent
 
26
        varname = assname.name
 
27
        before_stmts = get_statements(BEFORE_LOG_SOURCE % ((varname,) * 5))
 
28
        after_stmts = get_statements(AFTER_LOG_SOURCE % (varname, varname))
 
29
        stmt.insert_before(assign, before_stmts)
 
30
        stmt.insert_after(assign, after_stmts)
 
31
        return assname
 
32
 
 
33
 
 
34
def _trace(ast, enc, filename):
 
35
    return ast.accept(Tracer())
 
36
 
 
37
install_compiler_hook(_trace)
 
38
 
 
39
 
 
40
code = """
 
41
a = 3
 
42
b = 2
 
43
a = 1
 
44
"""
 
45
exec code