CommonImplementations.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. * Copyright (c) 2021-2023, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Bytecode/CommonImplementations.h>
  7. #include <LibJS/Bytecode/Interpreter.h>
  8. namespace JS::Bytecode {
  9. ThrowCompletionOr<NonnullGCPtr<Object>> base_object_for_get(Bytecode::Interpreter& interpreter, Value base_value)
  10. {
  11. auto& vm = interpreter.vm();
  12. if (base_value.is_object())
  13. return base_value.as_object();
  14. // OPTIMIZATION: For various primitives we can avoid actually creating a new object for them.
  15. if (base_value.is_string())
  16. return vm.current_realm()->intrinsics().string_prototype();
  17. if (base_value.is_number())
  18. return vm.current_realm()->intrinsics().number_prototype();
  19. if (base_value.is_boolean())
  20. return vm.current_realm()->intrinsics().boolean_prototype();
  21. return base_value.to_object(vm);
  22. }
  23. ThrowCompletionOr<Value> get_by_id(Bytecode::Interpreter& interpreter, IdentifierTableIndex property, Value base_value, Value this_value, u32 cache_index)
  24. {
  25. auto& vm = interpreter.vm();
  26. auto const& name = interpreter.current_executable().get_identifier(property);
  27. auto& cache = interpreter.current_executable().property_lookup_caches[cache_index];
  28. if (base_value.is_string()) {
  29. auto string_value = TRY(base_value.as_string().get(vm, name));
  30. if (string_value.has_value())
  31. return *string_value;
  32. }
  33. auto base_obj = TRY(base_object_for_get(interpreter, base_value));
  34. // OPTIMIZATION: If the shape of the object hasn't changed, we can use the cached property offset.
  35. // NOTE: Unique shapes don't change identity, so we compare their serial numbers instead.
  36. auto& shape = base_obj->shape();
  37. if (&shape == cache.shape
  38. && (!shape.is_unique() || shape.unique_shape_serial_number() == cache.unique_shape_serial_number)) {
  39. return base_obj->get_direct(cache.property_offset.value());
  40. }
  41. CacheablePropertyMetadata cacheable_metadata;
  42. auto value = TRY(base_obj->internal_get(name, this_value, &cacheable_metadata));
  43. if (cacheable_metadata.type == CacheablePropertyMetadata::Type::OwnProperty) {
  44. cache.shape = shape;
  45. cache.property_offset = cacheable_metadata.property_offset.value();
  46. cache.unique_shape_serial_number = shape.unique_shape_serial_number();
  47. }
  48. return value;
  49. }
  50. }