1""" GlobalDeclarations gathers top-level declarations. """
2
3from pythran.passmanager import ModuleAnalysis
4from beniget import DefUseChains
5
6
7class SilentDefUseChains(DefUseChains):
8
9    def unbound_identifier(self, name, node):
10        pass
11
12
13class GlobalDeclarations(ModuleAnalysis):
14
15    """ Gather all kind of identifier defined at global scope.
16
17    >>> import gast as ast
18    >>> from pythran import passmanager
19    >>> from pythran.analyses import GlobalDeclarations
20    >>> node = ast.parse('''
21    ... import math
22    ... import math as maths
23    ... from math import cos
24    ... c = 12
25    ... def foo(a):
26    ...     b = a + 1''')
27    >>> pm = passmanager.PassManager("test")
28    >>> sorted(pm.gather(GlobalDeclarations, node).keys())
29    ['c', 'cos', 'foo', 'math', 'maths']
30
31    """
32
33    def __init__(self):
34        """ Result is an identifier with matching definition. """
35        self.result = dict()
36        super(GlobalDeclarations, self).__init__()
37
38    def visit_Module(self, node):
39        """ Import module define a new variable name. """
40        duc = SilentDefUseChains()
41        duc.visit(node)
42        self.result = {d.name(): d.node
43                       for d in duc.locals[node]}
44