from pypy.rlib import rgc
from pypy.rlib.objectmodel import we_are_translated

from rupypy.module import Module, ModuleDef
from rupypy.objects.objectobject import W_BaseObject


def try_cast_gcref_to_w_baseobject(gcref):
    return rgc.try_cast_gcref_to_instance(W_BaseObject, gcref)


def clear_gcflag_extra(pending):
    while pending:
        gcref = pending.pop()
        if rgc.get_gcflag_extra(gcref):
            rgc.toggle_gcflag_extra(gcref)
            pending.extend(rgc.get_rpy_referents(gcref))


class ObjectSpace(Module):
    moduledef = ModuleDef("ObjectSpace")

    @moduledef.function("each_object")
    def method_each_object(self, space, w_mod, block):
        match_w = []
        if we_are_translated():
            roots = [gcref for gcref in rgc.get_rpy_roots() if gcref]
        else:
            roots = [rgc._GcRef(space)]
        pending = roots[:]
        while pending:
            gcref = pending.pop()
            if not rgc.get_gcflag_extra(gcref):
                rgc.toggle_gcflag_extra(gcref)
                w_obj = try_cast_gcref_to_w_baseobject(gcref)
                if w_obj is not None and space.is_kind_of(w_obj, w_mod):
                    match_w.append(w_obj)
                pending.extend(rgc.get_rpy_referents(gcref))
        clear_gcflag_extra(roots)
        for w_obj in match_w:
            space.invoke_block(block, [w_obj])

@@ -22,60 +22,8 @@
  rgc
-%0Afrom pypy.rlib.objectmodel import we_are_translated
 %0A%0Afr
@@ -639,44 +639,8 @@
  %5B%5D%0A
-        if we_are_translated():%0A    
     
@@ -705,62 +705,8 @@
 ef%5D%0A
-        else:%0A            roots = %5Brgc._GcRef(space)%5D%0A
     

Revert "fix ObjectSpace.each_object for me in untranslated mode"