test_parser.py :  » IDE » PyPE » PyPE-2.9.1 » Python Open Source

Home
Python Open Source
1.3.1.2 Python
2.Ajax
3.Aspect Oriented
4.Blog
5.Build
6.Business Application
7.Chart Report
8.Content Management Systems
9.Cryptographic
10.Database
11.Development
12.Editor
13.Email
14.ERP
15.Game 2D 3D
16.GIS
17.GUI
18.IDE
19.Installer
20.IRC
21.Issue Tracker
22.Language Interface
23.Log
24.Math
25.Media Sound Audio
26.Mobile
27.Network
28.Parser
29.PDF
30.Project Management
31.RSS
32.Search
33.Security
34.Template Engines
35.Test
36.UML
37.USB Serial
38.Web Frameworks
39.Web Server
40.Web Services
41.Web Unit
42.Wiki
43.Windows
44.XML
Python Open Source » IDE » PyPE 
PyPE » PyPE 2.9.1 » test_parser.py

'''
This software is licensed under the GPL (GNU General Public License) version 2
as it appears here: http://www.gnu.org/copyleft/gpl.html
It is also included with this archive as `gpl.txt <gpl.txt>`_.
'''


import compiler
from compiler import ast
from compiler import consts

def walk_ast(tree):
    transformer = Visitor()
    see = dict.fromkeys('Class Function'.split())
    stack = [(tree, 0)]
    while stack:
        tree, seen = stack.pop()
        if not isinstance(tree, ast.Node):
            continue
        name = tree.__class__.__name__
        if name in see:
            if seen:
                yield 'end',
                continue
            
            if hasattr(transformer, 'visit'+name):
                yield 'start', getattr(transformer, 'visit'+name)(tree), tree.lineno
            if tree.doc:
                yield 'doc', tree.doc
            stack.append((tree, 1))
        x = list(tree.getChildren())
        x.reverse()
        for i in x:
            if isinstance(i, ast.Node):
                stack.append((i, 0))

class Visitor:
    def visitClass(self, node):
        if node.bases:
            return 'class %s(%s):'%(node.name, ', '.join([i.name for i in node.bases]))
        return 'class %s:'%node.name
    
    def visitFunction(self, node):
        args = node.argnames[:]
        args2 = []
        if node.kwargs:
            args2.append('**'+args.pop())
        if node.varargs:
            args2.append('*'+args.pop())
        if node.defaults:
            d = node.defaults[:]
            while d:
                args2.append(args.pop()+'=?')
                _ = d.pop()
        
        args2.reverse()
        args += args2
        
        return 'def %s(%s):'%(node.name, ', '.join(args))

if __name__ == '__main__':
    a = '''import a, b, c

#I am a comment

# todo: I am a todo

def foo(x, y=6, *args,
        **kwargs):
    return None

class bar:
    def __init__(self, foo=a, bar=b):
        """blah!"""
'''
    x = compiler.parse(a)
    for y in walk_ast(x, Visitor()):
        print y
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.