Exemplo n.º 1
0
    def build_class(self, code):
        """Dump class definition, doc string and class body."""

        assert type(code) == CodeType
        code = Code(code, self.scanner, self.currentclass)
        #assert isinstance(code, Code)

        indent = self.indent
        #self.print_(indent, '#flags:\t', int(code.co_flags))
        ast = self.build_ast(code._tokens, code._customize)
        code._tokens = None # save memory
        assert ast == 'stmts'

        if ast[0][0] == NAME_MODULE:
            del ast[0]

        # if docstring exists, dump it
        if code.co_consts and code.co_consts[0] != None and ast[0][0] == ASSIGN_DOC_STRING(code.co_consts[0]):
            self.print_docstring(indent, code.co_consts[0])
            self.print_()
            del ast[0]
        

        # the function defining a class normally returns locals(); we
        # don't want this to show up in the source, thus remove the node
        if ast[-1][0] == RETURN_LOCALS:
            del ast[-1] # remove last node
        #else:
        #    print ast[-1][-1]

        for g in find_globals(ast, set()):
           self.print_(indent, 'global ', g)
           
        self.gen_source(ast, code._customize)
        code._tokens = None; code._customize = None # save memory
Exemplo n.º 2
0
    def build_class(self, code):
        """Dump class definition, doc string and class body."""

        assert type(code) == CodeType
        code = Code(code, self.scanner, self.currentclass)
        #assert isinstance(code, Code)

        indent = self.indent
        #self.print_(indent, '#flags:\t', int(code.co_flags))
        ast = self.build_ast(code._tokens, code._customize)
        code._tokens = None # save memory
        assert ast == 'stmts'

        if ast[0][0] == NAME_MODULE:
            del ast[0]

        # if docstring exists, dump it
        if code.co_consts and code.co_consts[0] != None and ast[0][0] == ASSIGN_DOC_STRING(code.co_consts[0]):
            self.print_docstring(indent, code.co_consts[0])
            self.print_()
            del ast[0]
        

        # the function defining a class normally returns locals(); we
        # don't want this to show up in the source, thus remove the node
        if ast[-1][0] == RETURN_LOCALS:
            del ast[-1] # remove last node
        #else:
        #    print ast[-1][-1]

        for g in find_globals(ast, {}).keys():
           self.print_(indent, 'global ', g)
           
        self.gen_source(ast, code._customize)
        code._tokens = None; code._customize = None # save memory
Exemplo n.º 3
0
    def build_class(self, code):
        """Dump class definition, doc string and class body."""

        assert type(code) == CodeType
        code = Code(code, self.scanner)
        #assert isinstance(code, Code)

        indent = self.indent
        #self.print_(indent, '#flags:\t', int(code.co_flags))
        ast = self.build_ast(code._tokens, code._customize)
        code._tokens = None  # save memory
        assert ast == 'stmts'

        # if docstring exists, dump it
        if code.co_consts[0] != None \
           and ast[0] == ASSIGN_DOC_STRING(code.co_consts[0]):
            #print '\n\n>>-->>doc string set\n\n'
            self.print_docstring(indent, code.co_consts[0])
            del ast[0]

        # the function defining a class normally returns locals(); we
        # don't want this to show up in the source, thus remove the node
        if ast[-1] == RETURN_LOCALS:
            ast.pop()  # remove last node

        for g in find_globals(ast, {}).keys():
            self.print_(indent, 'global ', g)
        self.gen_source(ast, code._customize)
        code._tokens = None
        code._customize = None  # save memory
Exemplo n.º 4
0
    def make_function(self, node, isLambda, nested=1):
        def build_param(ast, name, default):
            if name.startswith('.'):
                name = self.get_tuple_parameter(ast, name)
            if default:
                if self.showast:
                    print '--', name
                    print default
                    print '--'
                result = '%s = %s' % (name, self.traverse(default, indent=''))
                if result[-2:] == '= ':
                    result += 'None'
                return result
            else:
                return name

        defparams = node[:node[-1].attr]
        code = node[-2].attr
        assert type(code) == CodeType
        code = Code(code, self.scanner)
        ast = self.build_ast(code._tokens, code._customize)
        code._tokens = None
        assert ast == 'stmts'
        if isLambda:
            assert ast[-1] == 'stmt'
            assert len(ast[-1]) == 1
            assert ast[-1][0] == 'return_stmt'
            ast[-1][0].type = 'return_lambda'
        else:
            if ast[-1] == RETURN_NONE:
                ast.pop()
        argc = code.co_argcount
        paramnames = list(code.co_varnames[:argc])
        paramnames.reverse()
        defparams.reverse()
        params = []
        for name, default in map(lambda a, b: (a, b), paramnames, defparams):
            params.append(build_param(ast, name, default))
        params.reverse()
        if 4 & code.co_flags:
            params.append('*%s' % code.co_varnames[argc])
            argc += 1
        if 8 & code.co_flags:
            params.append('**%s' % code.co_varnames[argc])
            argc += 1
        indent = self.indent
        if isLambda:
            self.write("lambda ", ", ".join(params), ":")
        else:
            self.print_("(", ", ".join(params), "):")
        if code.co_consts[0] != None:
            self.print_docstring(indent, code.co_consts[0])
        for g in find_globals(ast, {}).keys():
            self.print_(indent, 'global ', g)
        self.gen_source(ast, code._customize, isLambda=isLambda)
        code._tokens = None
        code._customize = None
Exemplo n.º 5
0
 def build_class(self, code):
     assert type(code) == CodeType
     code = Code(code, self.scanner)
     indent = self.indent
     ast = self.build_ast(code._tokens, code._customize)
     code._tokens = None
     assert ast == 'stmts'
     if code.co_consts[0] != None \
        and ast[0] == ASSIGN_DOC_STRING(code.co_consts[0]):
         self.print_docstring(indent, code.co_consts[0])
         del ast[0]
     if ast[-1] == RETURN_LOCALS:
         ast.pop()
     for g in find_globals(ast, {}).keys():
         self.print_(indent, 'global ', g)
     self.gen_source(ast, code._customize)
     code._tokens = None
     code._customize = None
Exemplo n.º 6
0
    def make_function(self, node, isLambda, nested=1):
        """Dump function defintion, doc string, and function body."""

        def build_param(ast, name, default):
            """build parameters:
                - handle defaults
                - handle format tuple parameters
            """
            # if formal parameter is a tuple, the paramater name
            # starts with a dot (eg. '.1', '.2')
            if name.startswith('.'):
                # replace the name with the tuple-string
                name = self.get_tuple_parameter(ast, name)

            if default:
                if self.showast:
                    print '--', name
                    print default
                    print '--'
                result = '%s = %s' % (name, self.traverse(default, indent='') )
                if result[-2:] == '= ':	# default was 'LOAD_CONST None'
                    result += 'None'
                return result
            else:
                return name
        defparams = node[:node[-1].attr] # node[-1] == MAKE_xxx_n
        code = node[-2].attr

        assert type(code) == CodeType
        code = Code(code, self.scanner, self.currentclass)
        #assert isinstance(code, Code)

        # add defaults values to parameter names
        argc = code.co_argcount
        paramnames = list(code.co_varnames[:argc])

        # defaults are for last n parameters, thus reverse
        paramnames.reverse(); defparams.reverse()

        try:
            ast = self.build_ast(code._tokens,
                                 code._customize,
                                 isLambda = isLambda,
                                 noneInNames = ('None' in code.co_names))
        except ParserError as p:
            self.write( str(p))
            self.ERROR = p
            return
            
        # build parameters
       
        ##This would be a nicer piece of code, but I can't get this to work
        ## now, have to find a usable lambda constuct  hG/2000-09-05
        ##params = map(lambda name, default: build_param(ast, name, default),
        ##	     paramnames, defparams)
        params = []
        for name, default in map(lambda a,b: (a,b), paramnames, defparams):
            params.append( build_param(ast, name, default) )

        params.reverse() # back to correct order

        if 4 & code.co_flags:	# flag 2 -> variable number of args
            params.append('*%s' % code.co_varnames[argc])
            argc += 1
        if 8 & code.co_flags:	# flag 3 -> keyword args
            params.append('**%s' % code.co_varnames[argc])
            argc += 1

        # dump parameter list (with default values)
        indent = self.indent
        if isLambda:
            self.write("lambda ", ", ".join(params), ": ")
        else:
            self.print_("(", ", ".join(params), "):")
            #self.print_(indent, '#flags:\t', int(code.co_flags))

        if len(code.co_consts)>0 and code.co_consts[0] != None: 
            # docstring exists, dump it
            self.print_docstring(indent, code.co_consts[0])

        
        code._tokens = None # save memory
        assert ast == 'stmts'
        #if isLambda:
            # convert 'return' statement to expression
            #assert len(ast[0]) == 1  wrong, see 'lambda (r,b): r,b,g'
            #assert ast[-1] == 'stmt'
            #assert len(ast[-1]) == 1
#            assert ast[-1][0] == 'return_stmt'
#            ast[-1][0].type = 'return_lambda'
        #else:
        #    if ast[-1] == RETURN_NONE:
                # Python adds a 'return None' to the
                # end of any function; remove it
         #       ast.pop() # remove last node
        
        all_globals = find_all_globals(ast, set())
        for g in ((all_globals & self.mod_globs) | find_globals(ast, set())):
           self.print_(self.indent, 'global ', g)
        self.mod_globs -= all_globals
        rn = ('None' in code.co_names) and not find_none(ast)
        self.gen_source(ast, code._customize, isLambda=isLambda, returnNone=rn)
        code._tokens = None; code._customize = None # save memory
Exemplo n.º 7
0
    def make_function(self, node, isLambda, nested=1):
        """Dump function defintion, doc string, and function body."""
        def build_param(ast, name, default):
            """build parameters:
                - handle defaults
                - handle format tuple parameters
            """
            # if formal parameter is a tuple, the paramater name
            # starts with a dot (eg. '.1', '.2')
            if name.startswith('.'):
                # replace the name with the tuple-string
                name = self.get_tuple_parameter(ast, name)

            if default:
                if self.showast:
                    print '--', name
                    print default
                    print '--'
                result = '%s = %s' % (name, self.traverse(default, indent=''))
                if result[-2:] == '= ':  # default was 'LOAD_CONST None'
                    result += 'None'
                return result
            else:
                return name

        defparams = node[:node[-1].attr]  # node[-1] == MAKE_xxx_n
        code = node[-2].attr

        assert type(code) == CodeType
        code = Code(code, self.scanner, self.currentclass)
        #assert isinstance(code, Code)

        # add defaults values to parameter names
        argc = code.co_argcount
        paramnames = list(code.co_varnames[:argc])

        # defaults are for last n parameters, thus reverse
        paramnames.reverse()
        defparams.reverse()

        try:
            ast = self.build_ast(code._tokens,
                                 code._customize,
                                 isLambda=isLambda,
                                 noneInNames=('None' in code.co_names))
        except ParserError as p:
            self.write(str(p))
            self.ERROR = p
            return

        # build parameters

        ##This would be a nicer piece of code, but I can't get this to work
        ## now, have to find a usable lambda constuct  hG/2000-09-05
        ##params = map(lambda name, default: build_param(ast, name, default),
        ##	     paramnames, defparams)
        params = []
        for name, default in map(lambda a, b: (a, b), paramnames, defparams):
            params.append(build_param(ast, name, default))

        params.reverse()  # back to correct order

        if 4 & code.co_flags:  # flag 2 -> variable number of args
            params.append('*%s' % code.co_varnames[argc])
            argc += 1
        if 8 & code.co_flags:  # flag 3 -> keyword args
            params.append('**%s' % code.co_varnames[argc])
            argc += 1

        # dump parameter list (with default values)
        indent = self.indent
        if isLambda:
            self.write("lambda ", ", ".join(params), ": ")
        else:
            self.print_("(", ", ".join(params), "):")
            #self.print_(indent, '#flags:\t', int(code.co_flags))

        if len(code.co_consts
               ) > 0 and code.co_consts[0] != None and not isLambda:  # ugly
            # docstring exists, dump it
            self.print_docstring(indent, code.co_consts[0])

        code._tokens = None  # save memory
        assert ast == 'stmts'
        #if isLambda:
        # convert 'return' statement to expression
        #assert len(ast[0]) == 1  wrong, see 'lambda (r,b): r,b,g'
        #assert ast[-1] == 'stmt'
        #assert len(ast[-1]) == 1
        #            assert ast[-1][0] == 'return_stmt'
        #            ast[-1][0].type = 'return_lambda'
        #else:
        #    if ast[-1] == RETURN_NONE:
        # Python adds a 'return None' to the
        # end of any function; remove it
        #       ast.pop() # remove last node

        all_globals = find_all_globals(ast, set())
        for g in ((all_globals & self.mod_globs) | find_globals(ast, set())):
            self.print_(self.indent, 'global ', g)
        self.mod_globs -= all_globals
        rn = ('None' in code.co_names) and not find_none(ast)
        self.gen_source(ast, code._customize, isLambda=isLambda, returnNone=rn)
        code._tokens = None
        code._customize = None  # save memory