root / logilab.pylintinstaller / logilab / astng / astutils.py

Revision 202:d67e86292521, 2.4 kB (checked in by tziade@…, 9 months ago)

added logilab.pylintinstaller

Line 
1# Copyright (c) 2003 Sylvain Thenault (thenault@nerim.net)
2# Copyright (c) 2003 Logilab
3#
4# This program is free software; you can redistribute it and/or modify it under
5# the terms of the GNU General Public License as published by the Free Software
6# Foundation; either version 2 of the License, or (at your option) any later
7# version.
8#
9# This program is distributed in the hope that it will be useful, but WITHOUT
10# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
12#
13# You should have received a copy of the GNU General Public License along with
14# this program; if not, write to the Free Software Foundation, Inc.,
15# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
16"""Some usefull functions to manipulate ast tuples
17"""
18
19__author__ = u"Sylvain Thenault"
20
21import symbol
22import token
23from types import TupleType
24
25def debuild(ast_tuple):
26    """
27    reverse ast_tuple to string
28    """
29    if type(ast_tuple[1]) is TupleType:
30        result = ''
31        for child in ast_tuple[1:]: 
32            result = '%s%s' % (result, debuild(child))
33        return result
34    else:
35        return ast_tuple[1]
36
37def clean(ast_tuple):
38    """
39    reverse ast tuple to a list of tokens
40    merge sequences (token.NAME, token.DOT, token.NAME)
41    """
42    result = []
43    last = None
44    for couple in _clean(ast_tuple):
45        if couple[0] == token.NAME and last == token.DOT:
46            result[-1][1] += couple[1]
47        elif couple[0] == token.DOT and last == token.NAME:
48            result[-1][1] += couple[1]
49        else:
50            result.append(couple)
51        last = couple[0]
52    return result
53
54def _clean(ast_tuple):
55    """ transform the ast into as list of tokens (i.e. final elements)
56    """
57    if type(ast_tuple[1]) is TupleType:
58        v = []
59        for c in ast_tuple[1:]:
60            v += _clean(c)
61        return v
62    else:
63        return [list(ast_tuple[:2])]
64   
65def cvrtr(tuple):
66    """debug method returning an ast string in a readable fashion"""
67    if type(tuple) is TupleType:
68        try:
69            try:
70                txt = 'token.'+token.tok_name[tuple[0]]
71            except:
72                txt = 'symbol.'+symbol.sym_name[tuple[0]]
73        except:
74            txt =  'Unknown token/symbol'
75        return [txt] + map(cvrtr, tuple[1:])
76    else:
77        return tuple
78
79__all__ = ('debuild', 'clean', 'cvrtr')
Note: See TracBrowser for help on using the browser.