mirror of
https://github.com/LadybirdBrowser/ladybird.git
synced 2025-04-27 23:09:08 +00:00
This is a continuation of the previous two commits. As allocating a JS cell already primarily involves a realm instead of a global object, and we'll need to pass one to the allocate() function itself eventually (it's bridged via the global object right now), the create() functions need to receive a realm as well. The plan is for this to be the highest-level function that actually receives a realm and passes it around, AOs on an even higher level will use the "current realm" concept via VM::current_realm() as that's what the spec assumes; passing around realms (or global objects, for that matter) on higher AO levels is pointless and unlike for allocating individual objects, which may happen outside of regular JS execution, we don't need control over the specific realm that is being used there.
58 lines
1.7 KiB
C++
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.global_object(), value, *realm.global_object().weak_ref_prototype());
|
|
}
|
|
|
|
WeakRef* WeakRef::create(Realm& realm, Symbol& value)
|
|
{
|
|
return realm.heap().allocate<WeakRef>(realm.global_object(), value, *realm.global_object().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);
|
|
}
|
|
}
|
|
|
|
}
|