ladybird/Userland/Libraries/LibJS/Runtime/WeakRef.cpp
Linus Groh 50428ea8d2 LibJS: Move intrinsics to the realm
Intrinsics, i.e. mostly constructor and prototype objects, but also
things like empty and new object shape now live on a new heap-allocated
JS::Intrinsics object, thus completing the long journey of taking all
the magic away from the global object.
This represents the Realm's [[Intrinsics]] slot in the spec and matches
its existing [[GlobalObject]] / [[GlobalEnv]] slots in terms of
architecture.

In the majority of cases it should now be possibly to fully allocate a
regular object without the global object existing, and in fact that's
what we do now - the realm is allocated before the global object, and
the intrinsics between both :^)
2022-08-27 11:29:10 +01:00

58 lines
1.7 KiB
C++

/*
* Copyright (c) 2021-2022, Idan Horowitz <idan.horowitz@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibJS/Runtime/WeakRef.h>
namespace JS {
WeakRef* WeakRef::create(Realm& realm, Object& value)
{
return realm.heap().allocate<WeakRef>(realm, value, *realm.intrinsics().weak_ref_prototype());
}
WeakRef* WeakRef::create(Realm& realm, Symbol& value)
{
return realm.heap().allocate<WeakRef>(realm, value, *realm.intrinsics().weak_ref_prototype());
}
WeakRef::WeakRef(Object& value, Object& prototype)
: Object(prototype)
, WeakContainer(heap())
, m_value(&value)
, m_last_execution_generation(vm().execution_generation())
{
}
WeakRef::WeakRef(Symbol& value, Object& prototype)
: Object(prototype)
, WeakContainer(heap())
, m_value(&value)
, m_last_execution_generation(vm().execution_generation())
{
}
void WeakRef::remove_dead_cells(Badge<Heap>)
{
if (m_value.visit([](Cell* cell) -> bool { return cell->state() == Cell::State::Live; }, [](Empty) -> bool { VERIFY_NOT_REACHED(); }))
return;
m_value = Empty {};
// This is an optimization, we deregister from the garbage collector early (even if we were not garbage collected ourself yet)
// to reduce the garbage collection overhead, which we can do because a cleared weak ref cannot be reused.
WeakContainer::deregister();
}
void WeakRef::visit_edges(Visitor& visitor)
{
Base::visit_edges(visitor);
if (vm().execution_generation() == m_last_execution_generation) {
auto* cell = m_value.visit([](Cell* cell) -> Cell* { return cell; }, [](Empty) -> Cell* { return nullptr; });
visitor.visit(cell);
}
}
}