RegExpConstructor.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * Copyright (c) 2020, Matthew Olsson <mattco@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/Error.h>
  7. #include <LibJS/Runtime/GlobalObject.h>
  8. #include <LibJS/Runtime/RegExpConstructor.h>
  9. #include <LibJS/Runtime/RegExpObject.h>
  10. namespace JS {
  11. RegExpConstructor::RegExpConstructor(GlobalObject& global_object)
  12. : NativeFunction(vm().names.RegExp.as_string(), *global_object.function_prototype())
  13. {
  14. }
  15. void RegExpConstructor::initialize(GlobalObject& global_object)
  16. {
  17. auto& vm = this->vm();
  18. NativeFunction::initialize(global_object);
  19. // 22.2.4.1 RegExp.prototype, https://tc39.es/ecma262/#sec-regexp.prototype
  20. define_direct_property(vm.names.prototype, global_object.regexp_prototype(), 0);
  21. define_direct_property(vm.names.length, Value(2), Attribute::Configurable);
  22. define_native_accessor(*vm.well_known_symbol_species(), symbol_species_getter, {}, Attribute::Configurable);
  23. }
  24. RegExpConstructor::~RegExpConstructor()
  25. {
  26. }
  27. // 22.2.3.1 RegExp ( pattern, flags ), https://tc39.es/ecma262/#sec-regexp-pattern-flags
  28. Value RegExpConstructor::call()
  29. {
  30. return construct(*this);
  31. }
  32. // 22.2.3.1 RegExp ( pattern, flags ), https://tc39.es/ecma262/#sec-regexp-pattern-flags
  33. Value RegExpConstructor::construct(FunctionObject&)
  34. {
  35. auto& vm = this->vm();
  36. String pattern = "";
  37. String flags = "";
  38. if (!vm.argument(0).is_undefined()) {
  39. pattern = vm.argument(0).to_string(global_object());
  40. if (vm.exception())
  41. return {};
  42. }
  43. if (!vm.argument(1).is_undefined()) {
  44. flags = vm.argument(1).to_string(global_object());
  45. if (vm.exception())
  46. return {};
  47. }
  48. // FIXME: Use RegExpAlloc (which uses OrdinaryCreateFromConstructor)
  49. return RegExpObject::create(global_object(), pattern, flags);
  50. }
  51. // 22.2.4.2 get RegExp [ @@species ], https://tc39.es/ecma262/#sec-get-regexp-@@species
  52. JS_DEFINE_NATIVE_GETTER(RegExpConstructor::symbol_species_getter)
  53. {
  54. return vm.this_value(global_object);
  55. }
  56. }