Completed
Pull Request — master (#1116)
by Lasse
01:41
created

bears.c_languages.codeclone_detection.ClangASTPrintBear   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 53
Duplicated Lines 0 %
Metric Value
dl 0
loc 53
rs 10
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A run() 0 12 1
B print_node() 0 39 6
1
from coalib.bears.LocalBear import LocalBear
2
from coalib.bearlib.parsing.clang.cindex import Index, TranslationUnit
3
4
5
class ClangASTPrintBear(LocalBear):
6
    def print_node(self, cursor, filename, before="", spec_before=""):
7
        '''
8
        Prints this node and all child nodes recursively in the style of:
9
10
        -node
11
        |-child
12
        `-another child
13
         |-child of child
14
         `-last child of child
15
16
        :param cursor:      The node to print. (Clang cursor.)
17
        :param before:      What to print before the node.
18
        :param spec_before: What to print before this node but to replace with
19
                            spaces for child nodes.
20
        '''
21
        file = cursor.location.file
22
23
        if file is not None and file.name.decode() == filename:
24
            self.debug(
25
                before + spec_before + "-" + str(cursor.displayname.decode()),
26
                str(cursor.kind),
27
                "Lines",
28
                str(cursor.extent.start.line) + "-" +
29
                str(cursor.extent.end.line),
30
                "(" + " ".join(str(token.spelling.decode())
31
                               for token in cursor.get_tokens()) + ")")
32
33
        children = list(cursor.get_children())
34
35
        if len(children) > 0:
36
            for child in children[:-1]:
37
                self.print_node(child,
38
                                filename,
39
                                before + len(spec_before)*" " + "|")
40
41
            self.print_node(children[-1],
42
                            filename,
43
                            before + len(spec_before)*" ",
44
                            "`")
45
46
    def run(self,
47
            filename,
48
            file):
49
        """
50
        This bear is meant for debugging purposes relating to clang. It just
51
        prints out the whole AST for a file to the DEBUG channel.
52
        """
53
        root = Index.create().parse(
54
            filename,
55
            options=TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD).cursor
56
57
        self.print_node(root, filename)
58