pythonpythonparser.py 3.44 KB
Newer Older
1
#!/usr/bin/env python3
2 3 4 5 6 7 8
# -*- coding: utf-8 -*-

#
# This file is part of KDevelop
# Copyright 2010 Sven Brauch <svenbrauch@googlemail.com>
# Licensed under the GNU GPL
#
9

10 11 12 13 14
# This script once was used for parsing documents; that implementation is long gone.
# It's just kept for looking at the AST created by some code quickly; you can do this:
# echo 'foo = baz.bar(3, "str")' |./pythonpythonparser.py
# or similar to quickly see the AST for that code.

15 16
import ast
from xml.dom.minidom import Document
17
from lxml import etree
18
import types
19
import sys
20
import re
21 22

class KDevelopNodeVisitor(ast.NodeVisitor):
23
    basenode = etree.Element("pythonast")
24 25
    currentnode = None
    nodecnt = 0
26
    childNodeMap = {}
27 28 29 30
    
    def __init__(self, *arg, **args):
        super(KDevelopNodeVisitor, self).__init__(*arg, **args)
        self.currentnode = self.basenode
31
    
32 33 34
    def generic_visit(self, node):
        self.nodecnt += 1
        
35 36
        #self.childNodeMap[self.nodecnt] = node
        self.childNodeMap[node] = self.nodecnt
37
        
38 39 40
        node_xmlrepr = etree.Element(node.__class__.__name__ + "Ast")
        node_xmlrepr.set('nodecnt', str(self.nodecnt))
        self.currentnode.append(node_xmlrepr)
41 42 43 44 45 46 47 48 49 50
        
        save_currentnode = self.currentnode
        self.currentnode = node_xmlrepr
        
        fields = list(node._attributes)
        fields.extend(list(node._fields))
        
        searching_locally = []
        for field in fields:
            value = getattr(node, field)
Sven Brauch's avatar
Sven Brauch committed
51
            if type(value) not in [type(0), type(""), type(0.0), type(False)]:
52
                continue
53 54 55 56 57
            try:
                node_xmlrepr.set(field.lower(), str(value))
            except:
                sys.stderr.write("Warning: Invalid string literal replaced by empty string!\n")
                node_xmlrepr.set(field.lower(), "")
58

59 60 61

        super(KDevelopNodeVisitor, self).generic_visit(node)
        
62
        key = ''
63
        for field in fields:
64
            multiple_keys = []
65
            value = getattr(node, field)
Sven Brauch's avatar
Sven Brauch committed
66 67
            if type(value) not in [type(0), type(""), type(0.0), type(False)]:
                if type(value) == type([]):
68
                    for currentValue in value:
69 70 71
                        try:
                            multiple_keys.append(str(self.childNodeMap[currentValue]))
                        except KeyError:
72
                            sys.stderr.write("Warning: missing key on node " + str(node) + "\n")
73
                            multiple_keys.append('')
74
                    key = ','.join(multiple_keys)
75
                    node_xmlrepr.set("NRLST_" + field.lower(), str(key))
76
                else:
77 78 79
                    try:
                        key = self.childNodeMap[value]
                    except KeyError:
80
                        key = ''
81
                    node_xmlrepr.set("NR_" + field.lower(), str(key))
82 83
                
                
84 85
        self.currentnode = save_currentnode

86
f = sys.stdin.read()
87
v = KDevelopNodeVisitor()
88
try:
89
    parsetree = ast.parse(f)
90
except Exception as e:
91
    try:
92 93
        sys.stderr.write(str(e.lineno) + ':::' + str(e.offset))
        sys.stderr.write(":::" + str(type(e)).replace('<type \'exceptions.', '').replace('\'>', '') + ':::' + str(e.msg) + ": \"" + str(e.text).replace("\n", "") + "\"")
94
    except:
95
        sys.stderr.write('?:::?:::'+str(e)+':::?')
96
else:
97
    v.visit(parsetree)
Sven Brauch's avatar
Sven Brauch committed
98
    print(str(etree.tostring(v.basenode, xml_declaration=True, pretty_print=True, encoding='UTF-8')).replace('\\n', '\n'))