示例#1
0
    def new(self):
        self.name = self.ll_mod.name
        n = "__main__" if self.hlnode.is_main else self.hlnode.python_name
        self.v.ctx.add(c.Comment('Create module "{}" with __name__ "{}"'.format(self.hlnode.python_name, n)))
        self.v.ctx.add(
            c.Assignment(
                "=", c.ID(self.ll_mod.name), c.FuncCall(c.ID("PyModule_New"), c.ExprList(c.Constant("string", n)))
            )
        )
        self.fail_if_null(self.ll_mod.name)

        # get the modules dict
        mods = PyDictLL(None, self.v)
        mods.declare_tmp(name="_modules")
        self.v.ctx.add(c.Comment("Insert into sys.modules"))
        self.v.ctx.add(c.Assignment("=", c.ID(mods.name), c.FuncCall(c.ID("PyImport_GetModuleDict"), c.ExprList())))
        self.fail_if_null(self.ll_mod.name)
        mods.incref()

        # add ourself to the modules dict
        mods.set_item_string(n, self)

        # clear the ref so we don't free it later
        mods.clear()

        # grab the module dict
        self.v.ctx.add(
            c.Assignment(
                "=", c.ID(self.ll_dict.name), c.FuncCall(c.ID("PyModule_GetDict"), c.ExprList(c.ID(self.ll_mod.name)))
            )
        )
        self.fail_if_null(self.ll_dict.name)

        # set the builtins on the module
        self.set_attr_string("__builtins__", self.v.builtins)

        # set builtin properties
        self.set_initial_string_attribute("__name__", n)