Synopsis - Cross-Reference

File: /sandbox/bpl/decorate-functions.py
 1#! /usr/bin/env python
 2
 3import os, os.path, sys
 4sys.path.insert(0, os.getcwd())
 5
 6import PTree
 7import SymbolLookup
 8from Processor import *
 9
10class FunctionDecorator(PTree.Visitor):
11    """A FunctionDecorator walks over a parse tree and inserts comments at
12    the beginning of function definitions."""
13
14    def __init__(self, buffer):
15        super(FunctionDecorator, self).__init__()
16        self.__buffer = buffer
17
18    def visit_list(self, l):
19        if l.car():
20            l.car().accept(self)
21        if l.cdr():
22            l.cdr().accept(self)
23
24    def visit_declaration(self, d):
25        third = d.third()
26        if type(third) == PTree.Declarator and third.type.is_function:
27            body = d.nth(3);
28            # body.first() is '{', so we insert a comment after it
29            comment = '\n// this is the start of %s'%third.name
30            self.__buffer.insert(body.first(), comment)
31            body.accept(self)
32
33
34# create a buffer from the given input file
35test = os.path.join(os.path.dirname(__file__), 'functions.cc')
36buffer = Buffer(test)
37
38# create a lexer operating on that buffer, using std C++ with gcc extensions
39lexer = Lexer(buffer, TokenSet.CXX|TokenSet.GCC)
40
41# create a dummy symbol lookup table (will use a real one once it is fully functional
42symbols = SymbolLookup.Table(SymbolLookup.Language.NONE)
43
44# create a parser with the above lexer and symbol table, using the std C++ grammar
45parser = Parser(lexer, symbols, RuleSet.CXX)
46
47# generate a parser tree
48ptree = parser.parse()
49
50# walk over the parse tree to insert comments at the beginning of functions
51decorator = FunctionDecorator(buffer)
52ptree.accept(decorator)
53
54# write the modified buffer to the new file
55buffer.write('functions-dec.cc', '')