diff --git a/Libraries/LibJS/AST.cpp b/Libraries/LibJS/AST.cpp index a86937ba6a9..291fac8dfd0 100644 --- a/Libraries/LibJS/AST.cpp +++ b/Libraries/LibJS/AST.cpp @@ -63,7 +63,7 @@ static void print_indent(int indent) out("{}", ByteString::repeated(' ', indent * 2)); } -static void update_function_name(Value value, DeprecatedFlyString const& name) +static void update_function_name(Value value, FlyString const& name) { if (!value.is_function()) return; @@ -87,15 +87,15 @@ void LabelledStatement::dump(int indent) const } // 15.2.5 Runtime Semantics: InstantiateOrdinaryFunctionExpression, https://tc39.es/ecma262/#sec-runtime-semantics-instantiateordinaryfunctionexpression -Value FunctionExpression::instantiate_ordinary_function_expression(VM& vm, DeprecatedFlyString given_name) const +Value FunctionExpression::instantiate_ordinary_function_expression(VM& vm, FlyString given_name) const { auto& realm = *vm.current_realm(); if (given_name.is_empty()) - given_name = ""; + given_name = ""_fly_string; auto has_own_name = !name().is_empty(); - auto const used_name = has_own_name ? name() : given_name.view(); + auto const used_name = has_own_name ? name() : given_name; auto environment = GC::Ref { *vm.running_execution_context().lexical_environment }; if (has_own_name) { VERIFY(environment); @@ -117,10 +117,10 @@ Value FunctionExpression::instantiate_ordinary_function_expression(VM& vm, Depre return closure; } -Optional CallExpression::expression_string() const +Optional CallExpression::expression_string() const { if (is(*m_callee)) - return static_cast(*m_callee).string(); + return static_cast(*m_callee).string().to_string(); if (is(*m_callee)) return static_cast(*m_callee).to_string_approximation(); @@ -159,21 +159,20 @@ ThrowCompletionOr ClassMethod::class_element_evaluatio auto set_function_name = [&](ByteString prefix = "") { auto name = property_key_or_private_name.visit( - [&](PropertyKey const& property_key) -> ByteString { + [&](PropertyKey const& property_key) -> String { if (property_key.is_symbol()) { auto description = property_key.as_symbol()->description(); if (!description.has_value() || description->is_empty()) - return ""; - return ByteString::formatted("[{}]", *description); - } else { - return property_key.to_string(); + return ""_string; + return MUST(String::formatted("[{}]", *description)); } + return property_key.to_string(); }, - [&](PrivateName const& private_name) -> ByteString { - return private_name.description; + [&](PrivateName const& private_name) -> String { + return private_name.description.to_string(); }); - update_function_name(method_value, ByteString::formatted("{}{}{}", prefix, prefix.is_empty() ? "" : " ", name)); + update_function_name(method_value, MUST(String::formatted("{}{}{}", prefix, prefix.is_empty() ? "" : " ", name))); }; if (property_key_or_private_name.has()) { @@ -230,11 +229,11 @@ ThrowCompletionOr ClassField::class_element_evaluation if (m_initializer) { auto copy_initializer = m_initializer; auto name = property_key_or_private_name.visit( - [&](PropertyKey const& property_key) -> ByteString { + [&](PropertyKey const& property_key) -> String { return property_key.is_number() ? property_key.to_string() : property_key.to_string_or_symbol().to_display_string(); }, - [&](PrivateName const& private_name) -> ByteString { - return private_name.description; + [&](PrivateName const& private_name) -> String { + return private_name.description.to_string(); }); // FIXME: A potential optimization is not creating the functions here since these are never directly accessible. @@ -242,7 +241,7 @@ ThrowCompletionOr ClassField::class_element_evaluation FunctionParsingInsights parsing_insights; parsing_insights.uses_this_from_environment = true; parsing_insights.uses_this = true; - initializer = ECMAScriptFunctionObject::create(realm, "field", ByteString::empty(), *function_code, {}, 0, {}, vm.lexical_environment(), vm.running_execution_context().private_environment, FunctionKind::Normal, true, parsing_insights, false, property_key_or_private_name); + initializer = ECMAScriptFunctionObject::create(realm, "field"_string, ByteString::empty(), *function_code, {}, 0, {}, vm.lexical_environment(), vm.running_execution_context().private_environment, FunctionKind::Normal, true, parsing_insights, false, property_key_or_private_name); initializer->make_method(target); } @@ -254,19 +253,19 @@ ThrowCompletionOr ClassField::class_element_evaluation }; } -static Optional nullopt_or_private_identifier_description(Expression const& expression) +static Optional nullopt_or_private_identifier_description(Expression const& expression) { if (is(expression)) return static_cast(expression).string(); return {}; } -Optional ClassField::private_bound_identifier() const +Optional ClassField::private_bound_identifier() const { return nullopt_or_private_identifier_description(*m_key); } -Optional ClassMethod::private_bound_identifier() const +Optional ClassMethod::private_bound_identifier() const { return nullopt_or_private_identifier_description(*m_key); } @@ -289,7 +288,7 @@ ThrowCompletionOr StaticInitializer::class_element_eva FunctionParsingInsights parsing_insights; parsing_insights.uses_this_from_environment = true; parsing_insights.uses_this = true; - auto body_function = ECMAScriptFunctionObject::create(realm, ByteString::empty(), ByteString::empty(), *m_function_body, {}, 0, m_function_body->local_variables_names(), lexical_environment, private_environment, FunctionKind::Normal, true, parsing_insights, false); + auto body_function = ECMAScriptFunctionObject::create(realm, ""_string, ByteString::empty(), *m_function_body, {}, 0, m_function_body->local_variables_names(), lexical_environment, private_environment, FunctionKind::Normal, true, parsing_insights, false); // 6. Perform MakeMethod(bodyFunction, homeObject). body_function->make_method(home_object); @@ -298,7 +297,7 @@ ThrowCompletionOr StaticInitializer::class_element_eva return ClassValue { normal_completion(body_function) }; } -ThrowCompletionOr ClassExpression::create_class_constructor(VM& vm, Environment* class_environment, Environment* environment, Value super_class, ReadonlySpan element_keys, Optional const& binding_name, DeprecatedFlyString const& class_name) const +ThrowCompletionOr ClassExpression::create_class_constructor(VM& vm, Environment* class_environment, Environment* environment, Value super_class, ReadonlySpan element_keys, Optional const& binding_name, FlyString const& class_name) const { auto& realm = *vm.current_realm(); @@ -1209,16 +1208,16 @@ void MemberExpression::dump(int indent) const m_property->dump(indent + 1); } -ByteString MemberExpression::to_string_approximation() const +String MemberExpression::to_string_approximation() const { - ByteString object_string = ""; + String object_string = ""_string; if (is(*m_object)) - object_string = static_cast(*m_object).string(); + object_string = static_cast(*m_object).string().to_string(); if (is_computed()) - return ByteString::formatted("{}[]", object_string); + return MUST(String::formatted("{}[]", object_string)); if (is(*m_property)) - return ByteString::formatted("{}.{}", object_string, as(*m_property).string()); - return ByteString::formatted("{}.{}", object_string, as(*m_property).string()); + return MUST(String::formatted("{}.{}", object_string, as(*m_property).string())); + return MUST(String::formatted("{}.{}", object_string, as(*m_property).string())); } bool MemberExpression::ends_in_private_name() const @@ -1349,7 +1348,7 @@ void CatchClause::dump(int indent) const { print_indent(indent); m_parameter.visit( - [&](DeprecatedFlyString const& parameter) { + [&](FlyString const& parameter) { if (parameter.is_empty()) outln("CatchClause"); else @@ -1498,7 +1497,7 @@ void ScopeNode::add_hoisted_function(NonnullRefPtr de m_functions_hoistable_with_annexB_extension.append(move(declaration)); } -DeprecatedFlyString ExportStatement::local_name_for_default = "*default*"; +FlyString ExportStatement::local_name_for_default = "*default*"_fly_string; static void dump_assert_clauses(ModuleRequest const& request) { @@ -1516,7 +1515,7 @@ void ExportStatement::dump(int indent) const print_indent(indent + 1); outln("(ExportEntries)"); - auto string_or_null = [](Optional const& string) -> ByteString { + auto string_or_null = [](Optional const& string) -> ByteString { if (!string.has_value()) { return "null"; } @@ -1564,7 +1563,7 @@ void ImportStatement::dump(int indent) const } } -bool ExportStatement::has_export(DeprecatedFlyString const& export_name) const +bool ExportStatement::has_export(FlyString const& export_name) const { return any_of(m_entries.begin(), m_entries.end(), [&](auto& entry) { // Make sure that empty exported names does not overlap with anything @@ -1574,7 +1573,7 @@ bool ExportStatement::has_export(DeprecatedFlyString const& export_name) const }); } -bool ImportStatement::has_bound_name(DeprecatedFlyString const& name) const +bool ImportStatement::has_bound_name(FlyString const& name) const { return any_of(m_entries.begin(), m_entries.end(), [&](auto& entry) { return entry.local_name == name; @@ -1688,7 +1687,7 @@ ThrowCompletionOr Program::global_declaration_instantiation(VM& vm, Global Vector functions_to_initialize; // 7. Let declaredFunctionNames be a new empty List. - HashTable declared_function_names; + HashTable declared_function_names; // 8. For each element d of varDeclarations, in reverse List order, do @@ -1723,7 +1722,7 @@ ThrowCompletionOr Program::global_declaration_instantiation(VM& vm, Global })); // 9. Let declaredVarNames be a new empty List. - HashTable declared_var_names; + HashTable declared_var_names; // 10. For each element d of varDeclarations, do TRY(for_each_var_scoped_variable_declaration([&](Declaration const& declaration) { @@ -1853,7 +1852,7 @@ ThrowCompletionOr Program::global_declaration_instantiation(VM& vm, Global return {}; } -ModuleRequest::ModuleRequest(DeprecatedFlyString module_specifier_, Vector attributes) +ModuleRequest::ModuleRequest(FlyString module_specifier_, Vector attributes) : module_specifier(move(module_specifier_)) , attributes(move(attributes)) { diff --git a/Libraries/LibJS/AST.h b/Libraries/LibJS/AST.h index 09845cb36b8..e5f8fedfe45 100644 --- a/Libraries/LibJS/AST.h +++ b/Libraries/LibJS/AST.h @@ -9,7 +9,7 @@ #pragma once #include -#include +#include #include #include #include @@ -168,7 +168,7 @@ private: // 14.13 Labelled Statements, https://tc39.es/ecma262/#sec-labelled-statements class LabelledStatement final : public Statement { public: - LabelledStatement(SourceRange source_range, DeprecatedFlyString label, NonnullRefPtr labelled_item) + LabelledStatement(SourceRange source_range, FlyString label, NonnullRefPtr labelled_item) : Statement(move(source_range)) , m_label(move(label)) , m_labelled_item(move(labelled_item)) @@ -177,16 +177,16 @@ public: virtual void dump(int indent) const override; virtual Bytecode::CodeGenerationErrorOr> generate_bytecode(Bytecode::Generator&, Optional preferred_dst = {}) const override; - virtual Bytecode::CodeGenerationErrorOr> generate_labelled_evaluation(Bytecode::Generator&, Vector const&, Optional preferred_dst = {}) const; + virtual Bytecode::CodeGenerationErrorOr> generate_labelled_evaluation(Bytecode::Generator&, Vector const&, Optional preferred_dst = {}) const; - DeprecatedFlyString const& label() const { return m_label; } - DeprecatedFlyString& label() { return m_label; } + FlyString const& label() const { return m_label; } + FlyString& label() { return m_label; } NonnullRefPtr const& labelled_item() const { return m_labelled_item; } private: virtual bool is_labelled_statement() const final { return true; } - DeprecatedFlyString m_label; + FlyString m_label; NonnullRefPtr m_labelled_item; }; @@ -194,18 +194,18 @@ class LabelableStatement : public Statement { public: using Statement::Statement; - Vector const& labels() const { return m_labels; } - virtual void add_label(DeprecatedFlyString string) { m_labels.append(move(string)); } + Vector const& labels() const { return m_labels; } + virtual void add_label(FlyString string) { m_labels.append(move(string)); } protected: - Vector m_labels; + Vector m_labels; }; class IterationStatement : public Statement { public: using Statement::Statement; - virtual Bytecode::CodeGenerationErrorOr> generate_labelled_evaluation(Bytecode::Generator&, Vector const&, Optional preferred_dst = {}) const; + virtual Bytecode::CodeGenerationErrorOr> generate_labelled_evaluation(Bytecode::Generator&, Vector const&, Optional preferred_dst = {}) const; private: virtual bool is_iteration_statement() const final { return true; } @@ -325,8 +325,8 @@ public: ThrowCompletionOr for_each_function_hoistable_with_annexB_extension(ThrowCompletionOrVoidCallback&& callback) const; - Vector const& local_variables_names() const { return m_local_variables_names; } - size_t add_local_variable(DeprecatedFlyString name) + Vector const& local_variables_names() const { return m_local_variables_names; } + size_t add_local_variable(FlyString name) { auto index = m_local_variables_names.size(); m_local_variables_names.append(move(name)); @@ -348,15 +348,15 @@ private: Vector> m_functions_hoistable_with_annexB_extension; - Vector m_local_variables_names; + Vector m_local_variables_names; }; // ImportEntry Record, https://tc39.es/ecma262/#table-importentry-record-fields struct ImportEntry { - Optional import_name; // [[ImportName]]: stored string if Optional is not empty, NAMESPACE-OBJECT otherwise - DeprecatedFlyString local_name; // [[LocalName]] + Optional import_name; // [[ImportName]]: stored string if Optional is not empty, NAMESPACE-OBJECT otherwise + FlyString local_name; // [[LocalName]] - ImportEntry(Optional import_name_, DeprecatedFlyString local_name_) + ImportEntry(Optional import_name_, FlyString local_name_) : import_name(move(import_name_)) , local_name(move(local_name_)) { @@ -390,7 +390,7 @@ public: virtual Bytecode::CodeGenerationErrorOr> generate_bytecode(Bytecode::Generator&, Optional preferred_dst = {}) const override; - bool has_bound_name(DeprecatedFlyString const& name) const; + bool has_bound_name(FlyString const& name) const; Vector const& entries() const { return m_entries; } ModuleRequest const& module_request() const { return m_module_request; } @@ -412,10 +412,10 @@ struct ExportEntry { EmptyNamedExport, } kind; - Optional export_name; // [[ExportName]] - Optional local_or_import_name; // Either [[ImportName]] or [[LocalName]] + Optional export_name; // [[ExportName]] + Optional local_or_import_name; // Either [[ImportName]] or [[LocalName]] - ExportEntry(Kind export_kind, Optional export_name_, Optional local_or_import_name_) + ExportEntry(Kind export_kind, Optional export_name_, Optional local_or_import_name_) : kind(export_kind) , export_name(move(export_name_)) , local_or_import_name(move(local_or_import_name_)) @@ -427,7 +427,7 @@ struct ExportEntry { return m_module_request != nullptr; } - static ExportEntry indirect_export_entry(ModuleRequest const& module_request, Optional export_name, Optional import_name) + static ExportEntry indirect_export_entry(ModuleRequest const& module_request, Optional export_name, Optional import_name) { ExportEntry entry { Kind::NamedExport, move(export_name), move(import_name) }; entry.m_module_request = &module_request; @@ -445,7 +445,7 @@ private: friend class ExportStatement; public: - static ExportEntry named_export(DeprecatedFlyString export_name, DeprecatedFlyString local_name) + static ExportEntry named_export(FlyString export_name, FlyString local_name) { return ExportEntry { Kind::NamedExport, move(export_name), move(local_name) }; } @@ -455,7 +455,7 @@ public: return ExportEntry { Kind::ModuleRequestAllButDefault, {}, {} }; } - static ExportEntry all_module_request(DeprecatedFlyString export_name) + static ExportEntry all_module_request(FlyString export_name) { return ExportEntry { Kind::ModuleRequestAll, move(export_name), {} }; } @@ -468,7 +468,7 @@ public: class ExportStatement final : public Statement { public: - static DeprecatedFlyString local_name_for_default; + static FlyString local_name_for_default; ExportStatement(SourceRange source_range, RefPtr statement, Vector entries, bool is_default_export, Optional module_request) : Statement(move(source_range)) @@ -487,7 +487,7 @@ public: virtual Bytecode::CodeGenerationErrorOr> generate_bytecode(Bytecode::Generator&, Optional preferred_dst = {}) const override; - bool has_export(DeprecatedFlyString const& export_name) const; + bool has_export(FlyString const& export_name) const; bool has_statement() const { return m_statement; } Vector const& entries() const { return m_entries; } @@ -654,13 +654,13 @@ struct BindingPattern : RefCounted { class Identifier final : public Expression { public: - explicit Identifier(SourceRange source_range, DeprecatedFlyString string) + explicit Identifier(SourceRange source_range, FlyString string) : Expression(move(source_range)) , m_string(move(string)) { } - DeprecatedFlyString const& string() const { return m_string; } + FlyString const& string() const { return m_string; } bool is_local() const { return m_local_variable_index.has_value(); } size_t local_variable_index() const @@ -679,7 +679,7 @@ public: private: virtual bool is_identifier() const override { return true; } - DeprecatedFlyString m_string; + FlyString m_string; Optional m_local_variable_index; bool m_is_global { false }; @@ -701,13 +701,13 @@ struct FunctionParsingInsights { class FunctionNode { public: - StringView name() const { return m_name ? m_name->string().view() : ""sv; } + FlyString name() const { return m_name ? m_name->string() : ""_fly_string; } RefPtr name_identifier() const { return m_name; } ByteString const& source_text() const { return m_source_text; } Statement const& body() const { return *m_body; } Vector const& parameters() const { return m_parameters; } i32 function_length() const { return m_function_length; } - Vector const& local_variables_names() const { return m_local_variables_names; } + Vector const& local_variables_names() const { return m_local_variables_names; } bool is_strict_mode() const { return m_is_strict_mode; } bool might_need_arguments_object() const { return m_parsing_insights.might_need_arguments_object; } bool contains_direct_call_to_eval() const { return m_parsing_insights.contains_direct_call_to_eval; } @@ -717,12 +717,12 @@ public: bool uses_this_from_environment() const { return m_parsing_insights.uses_this_from_environment; } virtual bool has_name() const = 0; - virtual Value instantiate_ordinary_function_expression(VM&, DeprecatedFlyString given_name) const = 0; + virtual Value instantiate_ordinary_function_expression(VM&, FlyString given_name) const = 0; virtual ~FunctionNode() { } protected: - FunctionNode(RefPtr name, ByteString source_text, NonnullRefPtr body, Vector parameters, i32 function_length, FunctionKind kind, bool is_strict_mode, FunctionParsingInsights parsing_insights, bool is_arrow_function, Vector local_variables_names) + FunctionNode(RefPtr name, ByteString source_text, NonnullRefPtr body, Vector parameters, i32 function_length, FunctionKind kind, bool is_strict_mode, FunctionParsingInsights parsing_insights, bool is_arrow_function, Vector local_variables_names) : m_name(move(name)) , m_source_text(move(source_text)) , m_body(move(body)) @@ -752,7 +752,7 @@ private: bool m_is_arrow_function : 1 { false }; FunctionParsingInsights m_parsing_insights; - Vector m_local_variables_names; + Vector m_local_variables_names; }; class FunctionDeclaration final @@ -761,7 +761,7 @@ class FunctionDeclaration final public: static bool must_have_name() { return true; } - FunctionDeclaration(SourceRange source_range, RefPtr name, ByteString source_text, NonnullRefPtr body, Vector parameters, i32 function_length, FunctionKind kind, bool is_strict_mode, FunctionParsingInsights insights, Vector local_variables_names) + FunctionDeclaration(SourceRange source_range, RefPtr name, ByteString source_text, NonnullRefPtr body, Vector parameters, i32 function_length, FunctionKind kind, bool is_strict_mode, FunctionParsingInsights insights, Vector local_variables_names) : Declaration(move(source_range)) , FunctionNode(move(name), move(source_text), move(body), move(parameters), function_length, kind, is_strict_mode, insights, false, move(local_variables_names)) { @@ -777,7 +777,7 @@ public: void set_should_do_additional_annexB_steps() { m_is_hoisted = true; } bool has_name() const override { return true; } - Value instantiate_ordinary_function_expression(VM&, DeprecatedFlyString) const override { VERIFY_NOT_REACHED(); } + Value instantiate_ordinary_function_expression(VM&, FlyString) const override { VERIFY_NOT_REACHED(); } virtual ~FunctionDeclaration() { } @@ -791,7 +791,7 @@ class FunctionExpression final public: static bool must_have_name() { return false; } - FunctionExpression(SourceRange source_range, RefPtr name, ByteString source_text, NonnullRefPtr body, Vector parameters, i32 function_length, FunctionKind kind, bool is_strict_mode, FunctionParsingInsights insights, Vector local_variables_names, bool is_arrow_function = false) + FunctionExpression(SourceRange source_range, RefPtr name, ByteString source_text, NonnullRefPtr body, Vector parameters, i32 function_length, FunctionKind kind, bool is_strict_mode, FunctionParsingInsights insights, Vector local_variables_names, bool is_arrow_function = false) : Expression(move(source_range)) , FunctionNode(move(name), move(source_text), move(body), move(parameters), function_length, kind, is_strict_mode, insights, is_arrow_function, move(local_variables_names)) { @@ -804,7 +804,7 @@ public: bool has_name() const override { return !name().is_empty(); } - Value instantiate_ordinary_function_expression(VM&, DeprecatedFlyString given_name) const override; + Value instantiate_ordinary_function_expression(VM&, FlyString given_name) const override; virtual ~FunctionExpression() { } @@ -909,7 +909,7 @@ public: virtual void dump(int indent) const override; virtual Bytecode::CodeGenerationErrorOr> generate_bytecode(Bytecode::Generator&, Optional preferred_dst = {}) const override; - virtual Bytecode::CodeGenerationErrorOr> generate_labelled_evaluation(Bytecode::Generator&, Vector const&, Optional preferred_dst = {}) const override; + virtual Bytecode::CodeGenerationErrorOr> generate_labelled_evaluation(Bytecode::Generator&, Vector const&, Optional preferred_dst = {}) const override; private: NonnullRefPtr m_test; @@ -930,7 +930,7 @@ public: virtual void dump(int indent) const override; virtual Bytecode::CodeGenerationErrorOr> generate_bytecode(Bytecode::Generator&, Optional preferred_dst = {}) const override; - virtual Bytecode::CodeGenerationErrorOr> generate_labelled_evaluation(Bytecode::Generator&, Vector const&, Optional preferred_dst = {}) const override; + virtual Bytecode::CodeGenerationErrorOr> generate_labelled_evaluation(Bytecode::Generator&, Vector const&, Optional preferred_dst = {}) const override; private: NonnullRefPtr m_test; @@ -975,7 +975,7 @@ public: virtual void dump(int indent) const override; virtual Bytecode::CodeGenerationErrorOr> generate_bytecode(Bytecode::Generator&, Optional preferred_dst = {}) const override; - virtual Bytecode::CodeGenerationErrorOr> generate_labelled_evaluation(Bytecode::Generator&, Vector const&, Optional preferred_dst = {}) const override; + virtual Bytecode::CodeGenerationErrorOr> generate_labelled_evaluation(Bytecode::Generator&, Vector const&, Optional preferred_dst = {}) const override; private: RefPtr m_init; @@ -999,7 +999,7 @@ public: Statement const& body() const { return *m_body; } virtual Bytecode::CodeGenerationErrorOr> generate_bytecode(Bytecode::Generator&, Optional preferred_dst = {}) const override; - virtual Bytecode::CodeGenerationErrorOr> generate_labelled_evaluation(Bytecode::Generator&, Vector const&, Optional preferred_dst = {}) const override; + virtual Bytecode::CodeGenerationErrorOr> generate_labelled_evaluation(Bytecode::Generator&, Vector const&, Optional preferred_dst = {}) const override; virtual void dump(int indent) const override; private: @@ -1023,7 +1023,7 @@ public: Statement const& body() const { return *m_body; } virtual Bytecode::CodeGenerationErrorOr> generate_bytecode(Bytecode::Generator&, Optional preferred_dst = {}) const override; - virtual Bytecode::CodeGenerationErrorOr> generate_labelled_evaluation(Bytecode::Generator&, Vector const&, Optional preferred_dst = {}) const override; + virtual Bytecode::CodeGenerationErrorOr> generate_labelled_evaluation(Bytecode::Generator&, Vector const&, Optional preferred_dst = {}) const override; virtual void dump(int indent) const override; private: @@ -1043,7 +1043,7 @@ public: } virtual Bytecode::CodeGenerationErrorOr> generate_bytecode(Bytecode::Generator&, Optional preferred_dst = {}) const override; - virtual Bytecode::CodeGenerationErrorOr> generate_labelled_evaluation(Bytecode::Generator&, Vector const&, Optional preferred_dst = {}) const override; + virtual Bytecode::CodeGenerationErrorOr> generate_labelled_evaluation(Bytecode::Generator&, Vector const&, Optional preferred_dst = {}) const override; virtual void dump(int indent) const override; private: @@ -1228,7 +1228,7 @@ private: class StringLiteral final : public Expression { public: - explicit StringLiteral(SourceRange source_range, ByteString value) + explicit StringLiteral(SourceRange source_range, String value) : Expression(move(source_range)) , m_value(move(value)) { @@ -1237,12 +1237,12 @@ public: virtual void dump(int indent) const override; virtual Bytecode::CodeGenerationErrorOr> generate_bytecode(Bytecode::Generator&, Optional preferred_dst = {}) const override; - ByteString const& value() const { return m_value; } + String const& value() const { return m_value; } private: virtual bool is_string_literal() const override { return true; } - ByteString m_value; + String m_value; }; class NullLiteral final : public PrimitiveLiteral { @@ -1260,7 +1260,7 @@ public: class RegExpLiteral final : public Expression { public: - RegExpLiteral(SourceRange source_range, regex::Parser::Result parsed_regex, ByteString parsed_pattern, regex::RegexOptions parsed_flags, ByteString pattern, ByteString flags) + RegExpLiteral(SourceRange source_range, regex::Parser::Result parsed_regex, String parsed_pattern, regex::RegexOptions parsed_flags, String pattern, String flags) : Expression(move(source_range)) , m_parsed_regex(move(parsed_regex)) , m_parsed_pattern(move(parsed_pattern)) @@ -1274,35 +1274,35 @@ public: virtual Bytecode::CodeGenerationErrorOr> generate_bytecode(Bytecode::Generator&, Optional preferred_dst = {}) const override; regex::Parser::Result const& parsed_regex() const { return m_parsed_regex; } - ByteString const& parsed_pattern() const { return m_parsed_pattern; } + String const& parsed_pattern() const { return m_parsed_pattern; } regex::RegexOptions const& parsed_flags() const { return m_parsed_flags; } - ByteString const& pattern() const { return m_pattern; } - ByteString const& flags() const { return m_flags; } + String const& pattern() const { return m_pattern; } + String const& flags() const { return m_flags; } private: regex::Parser::Result m_parsed_regex; - ByteString m_parsed_pattern; + String m_parsed_pattern; regex::RegexOptions m_parsed_flags; - ByteString m_pattern; - ByteString m_flags; + String m_pattern; + String m_flags; }; class PrivateIdentifier final : public Expression { public: - explicit PrivateIdentifier(SourceRange source_range, DeprecatedFlyString string) + explicit PrivateIdentifier(SourceRange source_range, FlyString string) : Expression(move(source_range)) , m_string(move(string)) { } - DeprecatedFlyString const& string() const { return m_string; } + FlyString const& string() const { return m_string; } virtual void dump(int indent) const override; virtual bool is_private_identifier() const override { return true; } private: - DeprecatedFlyString m_string; + FlyString m_string; }; class ClassElement : public ASTNode { @@ -1326,7 +1326,7 @@ public: using ClassValue = Variant; virtual ThrowCompletionOr class_element_evaluation(VM&, Object& home_object, Value) const = 0; - virtual Optional private_bound_identifier() const { return {}; } + virtual Optional private_bound_identifier() const { return {}; } private: bool m_is_static { false }; @@ -1354,7 +1354,7 @@ public: virtual void dump(int indent) const override; virtual ThrowCompletionOr class_element_evaluation(VM&, Object& home_object, Value property_key) const override; - virtual Optional private_bound_identifier() const override; + virtual Optional private_bound_identifier() const override; private: virtual bool is_class_method() const override { return true; } @@ -1381,7 +1381,7 @@ public: virtual void dump(int indent) const override; virtual ThrowCompletionOr class_element_evaluation(VM&, Object& home_object, Value property_key) const override; - virtual Optional private_bound_identifier() const override; + virtual Optional private_bound_identifier() const override; private: NonnullRefPtr m_key; @@ -1433,7 +1433,7 @@ public: { } - StringView name() const { return m_name ? m_name->string().view() : ""sv; } + FlyString name() const { return m_name ? m_name->string() : ""_fly_string; } ByteString const& source_text() const { return m_source_text; } RefPtr constructor() const { return m_constructor; } @@ -1444,7 +1444,7 @@ public: bool has_name() const { return m_name; } - ThrowCompletionOr create_class_constructor(VM&, Environment* class_environment, Environment* environment, Value super_class, ReadonlySpan element_keys, Optional const& binding_name = {}, DeprecatedFlyString const& class_name = {}) const; + ThrowCompletionOr create_class_constructor(VM&, Environment* class_environment, Environment* environment, Value super_class, ReadonlySpan element_keys, Optional const& binding_name = {}, FlyString const& class_name = {}) const; private: virtual bool is_class_expression() const override { return true; } @@ -1473,7 +1473,7 @@ public: virtual bool is_lexical_declaration() const override { return true; } - StringView name() const { return m_class_expression->name(); } + FlyString name() const { return m_class_expression->name(); } private: virtual bool is_class_declaration() const override { return true; } @@ -1487,7 +1487,7 @@ private: // 10.2.1.3 Runtime Semantics: EvaluateBody, https://tc39.es/ecma262/#sec-runtime-semantics-evaluatebody class ClassFieldInitializerStatement final : public Statement { public: - ClassFieldInitializerStatement(SourceRange source_range, NonnullRefPtr expression, DeprecatedFlyString field_name) + ClassFieldInitializerStatement(SourceRange source_range, NonnullRefPtr expression, FlyString field_name) : Statement(move(source_range)) , m_expression(move(expression)) , m_class_field_identifier_name(move(field_name)) @@ -1499,7 +1499,7 @@ public: private: NonnullRefPtr m_expression; - DeprecatedFlyString m_class_field_identifier_name; // [[ClassFieldIdentifierName]] + FlyString m_class_field_identifier_name; // [[ClassFieldIdentifierName]] }; class SpreadExpression final : public Expression { @@ -1575,7 +1575,7 @@ protected: virtual bool is_call_expression() const override { return true; } - Optional expression_string() const; + Optional expression_string() const; NonnullRefPtr m_callee; }; @@ -1924,7 +1924,7 @@ public: Expression const& object() const { return *m_object; } Expression const& property() const { return *m_property; } - ByteString to_string_approximation() const; + [[nodiscard]] String to_string_approximation() const; bool ends_in_private_name() const; @@ -2040,7 +2040,7 @@ private: class CatchClause final : public ASTNode { public: - CatchClause(SourceRange source_range, DeprecatedFlyString parameter, NonnullRefPtr body) + CatchClause(SourceRange source_range, FlyString parameter, NonnullRefPtr body) : ASTNode(move(source_range)) , m_parameter(move(parameter)) , m_body(move(body)) @@ -2060,7 +2060,7 @@ public: virtual void dump(int indent) const override; private: - Variant> m_parameter; + Variant> m_parameter; NonnullRefPtr m_body; }; @@ -2130,7 +2130,7 @@ public: virtual void dump(int indent) const override; virtual Bytecode::CodeGenerationErrorOr> generate_bytecode(Bytecode::Generator&, Optional preferred_dst = {}) const override; - virtual Bytecode::CodeGenerationErrorOr> generate_labelled_evaluation(Bytecode::Generator&, Vector const&, Optional preferred_dst = {}) const; + virtual Bytecode::CodeGenerationErrorOr> generate_labelled_evaluation(Bytecode::Generator&, Vector const&, Optional preferred_dst = {}) const; void add_case(NonnullRefPtr switch_case) { m_cases.append(move(switch_case)); } @@ -2141,22 +2141,22 @@ private: class BreakStatement final : public Statement { public: - BreakStatement(SourceRange source_range, Optional target_label) + BreakStatement(SourceRange source_range, Optional target_label) : Statement(move(source_range)) , m_target_label(move(target_label)) { } - Optional const& target_label() const { return m_target_label; } + Optional const& target_label() const { return m_target_label; } virtual Bytecode::CodeGenerationErrorOr> generate_bytecode(Bytecode::Generator&, Optional preferred_dst = {}) const override; private: - Optional m_target_label; + Optional m_target_label; }; class ContinueStatement final : public Statement { public: - ContinueStatement(SourceRange source_range, Optional target_label) + ContinueStatement(SourceRange source_range, Optional target_label) : Statement(move(source_range)) , m_target_label(move(target_label)) { @@ -2164,10 +2164,10 @@ public: virtual Bytecode::CodeGenerationErrorOr> generate_bytecode(Bytecode::Generator&, Optional preferred_dst = {}) const override; - Optional const& target_label() const { return m_target_label; } + Optional const& target_label() const { return m_target_label; } private: - Optional m_target_label; + Optional m_target_label; }; class DebuggerStatement final : public Statement { diff --git a/Libraries/LibJS/Bytecode/ASTCodegen.cpp b/Libraries/LibJS/Bytecode/ASTCodegen.cpp index b56fbbfebd9..0ac609558d5 100644 --- a/Libraries/LibJS/Bytecode/ASTCodegen.cpp +++ b/Libraries/LibJS/Bytecode/ASTCodegen.cpp @@ -788,7 +788,7 @@ Bytecode::CodeGenerationErrorOr> LabelledStatement::gene // 14.13.4 Runtime Semantics: LabelledEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-labelledevaluation // LabelledStatement : LabelIdentifier : LabelledItem -Bytecode::CodeGenerationErrorOr> LabelledStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector const& label_set, [[maybe_unused]] Optional preferred_dst) const +Bytecode::CodeGenerationErrorOr> LabelledStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector const& label_set, [[maybe_unused]] Optional preferred_dst) const { Bytecode::Generator::SourceLocationScope scope(generator, *this); // Convert the m_labelled_item NNRP to a reference early so we don't have to do it every single time we want to use it. @@ -836,7 +836,7 @@ Bytecode::CodeGenerationErrorOr> LabelledStatement::gene return stmt_result; } -Bytecode::CodeGenerationErrorOr> IterationStatement::generate_labelled_evaluation(Bytecode::Generator&, Vector const&, [[maybe_unused]] Optional preferred_dst) const +Bytecode::CodeGenerationErrorOr> IterationStatement::generate_labelled_evaluation(Bytecode::Generator&, Vector const&, [[maybe_unused]] Optional preferred_dst) const { return Bytecode::CodeGenerationError { this, @@ -850,7 +850,7 @@ Bytecode::CodeGenerationErrorOr> WhileStatement::generat return generate_labelled_evaluation(generator, {}); } -Bytecode::CodeGenerationErrorOr> WhileStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector const& label_set, [[maybe_unused]] Optional preferred_dst) const +Bytecode::CodeGenerationErrorOr> WhileStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector const& label_set, [[maybe_unused]] Optional preferred_dst) const { Bytecode::Generator::SourceLocationScope scope(generator, *this); // test @@ -902,7 +902,7 @@ Bytecode::CodeGenerationErrorOr> DoWhileStatement::gener return generate_labelled_evaluation(generator, {}); } -Bytecode::CodeGenerationErrorOr> DoWhileStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector const& label_set, [[maybe_unused]] Optional preferred_dst) const +Bytecode::CodeGenerationErrorOr> DoWhileStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector const& label_set, [[maybe_unused]] Optional preferred_dst) const { Bytecode::Generator::SourceLocationScope scope(generator, *this); // jump always (true) body @@ -960,7 +960,7 @@ Bytecode::CodeGenerationErrorOr> ForStatement::generate_ return generate_labelled_evaluation(generator, {}); } -Bytecode::CodeGenerationErrorOr> ForStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector const& label_set, [[maybe_unused]] Optional preferred_dst) const +Bytecode::CodeGenerationErrorOr> ForStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector const& label_set, [[maybe_unused]] Optional preferred_dst) const { Bytecode::Generator::SourceLocationScope scope(generator, *this); // init @@ -1142,17 +1142,17 @@ Bytecode::CodeGenerationErrorOr> ObjectExpression::gener if (is(property->key())) { auto& string_literal = static_cast(property->key()); - Bytecode::IdentifierTableIndex key_name = generator.intern_identifier(string_literal.value()); + Bytecode::IdentifierTableIndex key_name = generator.intern_identifier(MUST(FlyString::from_utf8(string_literal.value().bytes()))); Optional value; if (property_kind == Bytecode::Op::PropertyKind::ProtoSetter) { value = TRY(property->value().generate_bytecode(generator)).value(); } else { - ByteString identifier = string_literal.value(); + auto identifier = string_literal.value(); if (property_kind == Bytecode::Op::PropertyKind::Getter) - identifier = ByteString::formatted("get {}", identifier); + identifier = MUST(String::formatted("get {}", identifier)); else if (property_kind == Bytecode::Op::PropertyKind::Setter) - identifier = ByteString::formatted("set {}", identifier); + identifier = MUST(String::formatted("set {}", identifier)); auto name = generator.intern_identifier(identifier); value = TRY(generator.emit_named_evaluation_if_anonymous_function(property->value(), name)).value(); } @@ -1846,8 +1846,8 @@ Bytecode::CodeGenerationErrorOr> ReturnStatement::genera auto received_completion_type = generator.allocate_register(); auto received_completion_value = generator.allocate_register(); - auto type_identifier = generator.intern_identifier("type"); - auto value_identifier = generator.intern_identifier("value"); + auto type_identifier = generator.intern_identifier("type"_fly_string); + auto value_identifier = generator.intern_identifier("value"_fly_string); return_value = generate_await(generator, *return_value, received_completion, received_completion_type, received_completion_value, type_identifier, value_identifier); } @@ -1966,8 +1966,8 @@ Bytecode::CodeGenerationErrorOr> YieldExpression::genera auto received_completion_type = generator.allocate_register(); auto received_completion_value = generator.allocate_register(); - auto type_identifier = generator.intern_identifier("type"); - auto value_identifier = generator.intern_identifier("value"); + auto type_identifier = generator.intern_identifier("type"_fly_string); + auto value_identifier = generator.intern_identifier("value"_fly_string); if (m_is_yield_from) { // 15.5.5 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-generator-function-definitions-runtime-semantics-evaluation @@ -2102,7 +2102,7 @@ Bytecode::CodeGenerationErrorOr> YieldExpression::genera // i. Let throw be ? GetMethod(iterator, "throw"). auto throw_method = generator.allocate_register(); - generator.emit(throw_method, iterator, generator.intern_identifier("throw")); + generator.emit(throw_method, iterator, generator.intern_identifier("throw"_fly_string)); // ii. If throw is not undefined, then auto& throw_method_is_defined_block = generator.make_block(); @@ -2187,7 +2187,7 @@ Bytecode::CodeGenerationErrorOr> YieldExpression::genera // ii. Let return be ? GetMethod(iterator, "return"). auto return_method = generator.allocate_register(); - generator.emit(return_method, iterator, generator.intern_identifier("return")); + generator.emit(return_method, iterator, generator.intern_identifier("return"_fly_string)); // iii. If return is undefined, then auto& return_is_undefined_block = generator.make_block(); @@ -2542,7 +2542,7 @@ Bytecode::CodeGenerationErrorOr> TaggedTemplateLiteral:: generator.emit_with_extra_operand_slots(raw_string_regs.size(), raw_strings_array, raw_string_regs); } - generator.emit(strings_array, generator.intern_identifier("raw"), raw_strings_array, Bytecode::Op::PropertyKind::KeyValue, generator.next_property_lookup_cache()); + generator.emit(strings_array, generator.intern_identifier("raw"_fly_string), raw_strings_array, Bytecode::Op::PropertyKind::KeyValue, generator.next_property_lookup_cache()); auto arguments = generator.allocate_register(); if (!argument_regs.is_empty()) @@ -2661,7 +2661,7 @@ Bytecode::CodeGenerationErrorOr> TryStatement::generate_ bool did_create_variable_scope_for_catch_clause = false; TRY(m_handler->parameter().visit( - [&](DeprecatedFlyString const& parameter) -> Bytecode::CodeGenerationErrorOr { + [&](FlyString const& parameter) -> Bytecode::CodeGenerationErrorOr { if (!parameter.is_empty()) { generator.begin_variable_scope(); did_create_variable_scope_for_catch_clause = true; @@ -2762,7 +2762,7 @@ Bytecode::CodeGenerationErrorOr> SwitchStatement::genera return generate_labelled_evaluation(generator, {}); } -Bytecode::CodeGenerationErrorOr> SwitchStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector const& label_set, [[maybe_unused]] Optional preferred_dst) const +Bytecode::CodeGenerationErrorOr> SwitchStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector const& label_set, [[maybe_unused]] Optional preferred_dst) const { Bytecode::Generator::SourceLocationScope scope(generator, *this); @@ -2989,8 +2989,8 @@ Bytecode::CodeGenerationErrorOr> AwaitExpression::genera generator.emit(received_completion, generator.accumulator()); - auto type_identifier = generator.intern_identifier("type"); - auto value_identifier = generator.intern_identifier("value"); + auto type_identifier = generator.intern_identifier("type"_fly_string); + auto value_identifier = generator.intern_identifier("value"_fly_string); return generate_await(generator, argument, received_completion, received_completion_type, received_completion_value, type_identifier, value_identifier); } @@ -3144,7 +3144,7 @@ static Bytecode::CodeGenerationErrorOr for_in_of_he } // 14.7.5.7 ForIn/OfBodyEvaluation ( lhs, stmt, iteratorRecord, iterationKind, lhsKind, labelSet [ , iteratorKind ] ), https://tc39.es/ecma262/#sec-runtime-semantics-forin-div-ofbodyevaluation-lhs-stmt-iterator-lhskind-labelset -static Bytecode::CodeGenerationErrorOr> for_in_of_body_evaluation(Bytecode::Generator& generator, ASTNode const& node, Variant, NonnullRefPtr> const& lhs, ASTNode const& body, ForInOfHeadEvaluationResult const& head_result, Vector const& label_set, Bytecode::BasicBlock& loop_end, Bytecode::BasicBlock& loop_update, IteratorHint iterator_kind = IteratorHint::Sync, [[maybe_unused]] Optional preferred_dst = {}) +static Bytecode::CodeGenerationErrorOr> for_in_of_body_evaluation(Bytecode::Generator& generator, ASTNode const& node, Variant, NonnullRefPtr> const& lhs, ASTNode const& body, ForInOfHeadEvaluationResult const& head_result, Vector const& label_set, Bytecode::BasicBlock& loop_end, Bytecode::BasicBlock& loop_update, IteratorHint iterator_kind = IteratorHint::Sync, [[maybe_unused]] Optional preferred_dst = {}) { // 1. If iteratorKind is not present, set iteratorKind to sync. @@ -3186,8 +3186,8 @@ static Bytecode::CodeGenerationErrorOr> for_in_of_body_e auto received_completion_type = generator.allocate_register(); auto received_completion_value = generator.allocate_register(); - auto type_identifier = generator.intern_identifier("type"); - auto value_identifier = generator.intern_identifier("value"); + auto type_identifier = generator.intern_identifier("type"_fly_string); + auto value_identifier = generator.intern_identifier("value"_fly_string); generator.emit(received_completion, generator.accumulator()); auto new_result = generate_await(generator, next_result, received_completion, received_completion_type, received_completion_value, type_identifier, value_identifier); @@ -3377,7 +3377,7 @@ Bytecode::CodeGenerationErrorOr> ForInStatement::generat } // 14.7.5.5 Runtime Semantics: ForInOfLoopEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-forinofloopevaluation -Bytecode::CodeGenerationErrorOr> ForInStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector const& label_set, [[maybe_unused]] Optional preferred_dst) const +Bytecode::CodeGenerationErrorOr> ForInStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector const& label_set, [[maybe_unused]] Optional preferred_dst) const { auto& loop_end = generator.make_block(); auto& loop_update = generator.make_block(); @@ -3393,7 +3393,7 @@ Bytecode::CodeGenerationErrorOr> ForOfStatement::generat return generate_labelled_evaluation(generator, {}); } -Bytecode::CodeGenerationErrorOr> ForOfStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector const& label_set, [[maybe_unused]] Optional preferred_dst) const +Bytecode::CodeGenerationErrorOr> ForOfStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector const& label_set, [[maybe_unused]] Optional preferred_dst) const { auto& loop_end = generator.make_block(); auto& loop_update = generator.make_block(); @@ -3409,7 +3409,7 @@ Bytecode::CodeGenerationErrorOr> ForAwaitOfStatement::ge return generate_labelled_evaluation(generator, {}); } -Bytecode::CodeGenerationErrorOr> ForAwaitOfStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector const& label_set, [[maybe_unused]] Optional preferred_dst) const +Bytecode::CodeGenerationErrorOr> ForAwaitOfStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector const& label_set, [[maybe_unused]] Optional preferred_dst) const { auto& loop_end = generator.make_block(); auto& loop_update = generator.make_block(); @@ -3561,7 +3561,7 @@ Bytecode::CodeGenerationErrorOr> ExportStatement::genera } if (is(*m_statement)) { - auto value = TRY(generator.emit_named_evaluation_if_anonymous_function(static_cast(*m_statement), generator.intern_identifier("default"sv))).value(); + auto value = TRY(generator.emit_named_evaluation_if_anonymous_function(static_cast(*m_statement), generator.intern_identifier("default"_fly_string))).value(); if (!static_cast(*m_statement).has_name()) { generator.emit( @@ -3574,7 +3574,7 @@ Bytecode::CodeGenerationErrorOr> ExportStatement::genera // ExportDeclaration : export default AssignmentExpression ; VERIFY(is(*m_statement)); - auto value = TRY(generator.emit_named_evaluation_if_anonymous_function(static_cast(*m_statement), generator.intern_identifier("default"sv))).value(); + auto value = TRY(generator.emit_named_evaluation_if_anonymous_function(static_cast(*m_statement), generator.intern_identifier("default"_fly_string))).value(); generator.emit( generator.intern_identifier(ExportStatement::local_name_for_default), value); diff --git a/Libraries/LibJS/Bytecode/Executable.h b/Libraries/LibJS/Bytecode/Executable.h index c6efe7c93c1..d60268980c5 100644 --- a/Libraries/LibJS/Bytecode/Executable.h +++ b/Libraries/LibJS/Bytecode/Executable.h @@ -6,7 +6,7 @@ #pragma once -#include +#include #include #include #include @@ -60,7 +60,7 @@ public: virtual ~Executable() override; - DeprecatedFlyString name; + FlyString name; Vector bytecode; Vector property_lookup_caches; Vector global_variable_caches; @@ -85,15 +85,15 @@ public: HashMap source_map; - Vector local_variable_names; + Vector local_variable_names; size_t local_index_base { 0 }; Optional length_identifier; - ByteString const& get_string(StringTableIndex index) const { return string_table->get(index); } - DeprecatedFlyString const& get_identifier(IdentifierTableIndex index) const { return identifier_table->get(index); } + String const& get_string(StringTableIndex index) const { return string_table->get(index); } + FlyString const& get_identifier(IdentifierTableIndex index) const { return identifier_table->get(index); } - Optional get_identifier(Optional const& index) const + Optional get_identifier(Optional const& index) const { if (!index.has_value()) return {}; diff --git a/Libraries/LibJS/Bytecode/Generator.cpp b/Libraries/LibJS/Bytecode/Generator.cpp index 930b0c6264b..1c9d50f8508 100644 --- a/Libraries/LibJS/Bytecode/Generator.cpp +++ b/Libraries/LibJS/Bytecode/Generator.cpp @@ -56,7 +56,7 @@ CodeGenerationErrorOr Generator::emit_function_declaration_instantiation(E if (function.m_arguments_object_needed) { Optional dst; - auto local_var_index = function.m_local_variables_names.find_first_index("arguments"sv); + auto local_var_index = function.m_local_variables_names.find_first_index("arguments"_fly_string); if (local_var_index.has_value()) dst = local(local_var_index.value()); @@ -219,7 +219,7 @@ CodeGenerationErrorOr Generator::emit_function_declaration_instantiation(E return {}; } -CodeGenerationErrorOr> Generator::compile(VM& vm, ASTNode const& node, FunctionKind enclosing_function_kind, GC::Ptr function, MustPropagateCompletion must_propagate_completion, Vector local_variable_names) +CodeGenerationErrorOr> Generator::compile(VM& vm, ASTNode const& node, FunctionKind enclosing_function_kind, GC::Ptr function, MustPropagateCompletion must_propagate_completion, Vector local_variable_names) { Generator generator(vm, function, must_propagate_completion); @@ -482,7 +482,7 @@ CodeGenerationErrorOr> Generator::compile(VM& vm, ASTNode co CodeGenerationErrorOr> Generator::generate_from_ast_node(VM& vm, ASTNode const& node, FunctionKind enclosing_function_kind) { - Vector local_variable_names; + Vector local_variable_names; if (is(node)) local_variable_names = static_cast(node).local_variables_names(); return compile(vm, node, enclosing_function_kind, {}, MustPropagateCompletion::Yes, move(local_variable_names)); @@ -588,7 +588,7 @@ void Generator::end_variable_scope() } } -void Generator::begin_continuable_scope(Label continue_target, Vector const& language_label_set) +void Generator::begin_continuable_scope(Label continue_target, Vector const& language_label_set) { m_continuable_scopes.append({ continue_target, language_label_set }); start_boundary(BlockBoundaryType::Continue); @@ -605,7 +605,7 @@ Label Generator::nearest_breakable_scope() const return m_breakable_scopes.last().bytecode_target; } -void Generator::begin_breakable_scope(Label breakable_target, Vector const& language_label_set) +void Generator::begin_breakable_scope(Label breakable_target, Vector const& language_label_set) { m_breakable_scopes.append({ breakable_target, language_label_set }); start_boundary(BlockBoundaryType::Break); @@ -902,21 +902,21 @@ void Generator::emit_set_variable(JS::Identifier const& identifier, ScopedOperan } } -static Optional expression_identifier(Expression const& expression) +static Optional expression_identifier(Expression const& expression) { if (expression.is_identifier()) { auto const& identifier = static_cast(expression); - return identifier.string(); + return identifier.string().to_string(); } if (expression.is_numeric_literal()) { auto const& literal = static_cast(expression); - return literal.value().to_string_without_side_effects().to_byte_string(); + return literal.value().to_string_without_side_effects(); } if (expression.is_string_literal()) { auto const& literal = static_cast(expression); - return ByteString::formatted("'{}'", literal.value()); + return MUST(String::formatted("'{}'", literal.value())); } if (expression.is_member_expression()) { @@ -933,7 +933,7 @@ static Optional expression_identifier(Expression const& expression) builder.appendff(".{}", *identifer); } - return builder.to_byte_string(); + return builder.to_string_without_validation(); } return {}; @@ -996,7 +996,7 @@ void Generator::generate_scoped_jump(JumpType type) VERIFY_NOT_REACHED(); } -void Generator::generate_labelled_jump(JumpType type, DeprecatedFlyString const& label) +void Generator::generate_labelled_jump(JumpType type, FlyString const& label) { TemporaryChange temp { m_current_unwind_context, m_current_unwind_context }; size_t current_boundary = m_boundaries.size(); @@ -1047,7 +1047,7 @@ void Generator::generate_break() generate_scoped_jump(JumpType::Break); } -void Generator::generate_break(DeprecatedFlyString const& break_label) +void Generator::generate_break(FlyString const& break_label) { generate_labelled_jump(JumpType::Break, break_label); } @@ -1057,7 +1057,7 @@ void Generator::generate_continue() generate_scoped_jump(JumpType::Continue); } -void Generator::generate_continue(DeprecatedFlyString const& continue_label) +void Generator::generate_continue(FlyString const& continue_label) { generate_labelled_jump(JumpType::Continue, continue_label); } @@ -1121,12 +1121,12 @@ void Generator::emit_get_by_id_with_this(ScopedOperand dst, ScopedOperand base, void Generator::emit_iterator_value(ScopedOperand dst, ScopedOperand result) { - emit_get_by_id(dst, result, intern_identifier("value"sv)); + emit_get_by_id(dst, result, intern_identifier("value"_fly_string)); } void Generator::emit_iterator_complete(ScopedOperand dst, ScopedOperand result) { - emit_get_by_id(dst, result, intern_identifier("done"sv)); + emit_get_by_id(dst, result, intern_identifier("done"_fly_string)); } bool Generator::is_local_initialized(u32 local_index) const diff --git a/Libraries/LibJS/Bytecode/Generator.h b/Libraries/LibJS/Bytecode/Generator.h index 166eb1fc981..27ad0efdda2 100644 --- a/Libraries/LibJS/Bytecode/Generator.h +++ b/Libraries/LibJS/Bytecode/Generator.h @@ -153,9 +153,9 @@ public: CodeGenerationErrorOr> emit_named_evaluation_if_anonymous_function(Expression const&, Optional lhs_name, Optional preferred_dst = {}); - void begin_continuable_scope(Label continue_target, Vector const& language_label_set); + void begin_continuable_scope(Label continue_target, Vector const& language_label_set); void end_continuable_scope(); - void begin_breakable_scope(Label breakable_target, Vector const& language_label_set); + void begin_breakable_scope(Label breakable_target, Vector const& language_label_set); void end_breakable_scope(); [[nodiscard]] Label nearest_continuable_scope() const; @@ -188,7 +188,7 @@ public: return m_current_basic_block->is_terminated(); } - StringTableIndex intern_string(ByteString string) + StringTableIndex intern_string(String string) { return m_string_table->insert(move(string)); } @@ -198,7 +198,7 @@ public: return m_regex_table->insert(move(regex)); } - IdentifierTableIndex intern_identifier(DeprecatedFlyString string) + IdentifierTableIndex intern_identifier(FlyString string) { return m_identifier_table->insert(move(string)); } @@ -265,10 +265,10 @@ public: bool must_enter_finalizer() const { return m_boundaries.contains_slow(BlockBoundaryType::ReturnToFinally); } void generate_break(); - void generate_break(DeprecatedFlyString const& break_label); + void generate_break(FlyString const& break_label); void generate_continue(); - void generate_continue(DeprecatedFlyString const& continue_label); + void generate_continue(FlyString const& continue_label); template void emit_return(ScopedOperand value) @@ -343,14 +343,14 @@ public: private: VM& m_vm; - static CodeGenerationErrorOr> compile(VM&, ASTNode const&, FunctionKind, GC::Ptr, MustPropagateCompletion, Vector local_variable_names); + static CodeGenerationErrorOr> compile(VM&, ASTNode const&, FunctionKind, GC::Ptr, MustPropagateCompletion, Vector local_variable_names); enum class JumpType { Continue, Break, }; void generate_scoped_jump(JumpType); - void generate_labelled_jump(JumpType, DeprecatedFlyString const& label); + void generate_labelled_jump(JumpType, FlyString const& label); Generator(VM&, GC::Ptr, MustPropagateCompletion); ~Generator() = default; @@ -362,7 +362,7 @@ private: struct LabelableScope { Label bytecode_target; - Vector language_label_set; + Vector language_label_set; }; BasicBlock* m_current_basic_block { nullptr }; diff --git a/Libraries/LibJS/Bytecode/IdentifierTable.cpp b/Libraries/LibJS/Bytecode/IdentifierTable.cpp index 121bbacab2a..033d8dc6d8a 100644 --- a/Libraries/LibJS/Bytecode/IdentifierTable.cpp +++ b/Libraries/LibJS/Bytecode/IdentifierTable.cpp @@ -8,14 +8,14 @@ namespace JS::Bytecode { -IdentifierTableIndex IdentifierTable::insert(DeprecatedFlyString string) +IdentifierTableIndex IdentifierTable::insert(FlyString string) { m_identifiers.append(move(string)); VERIFY(m_identifiers.size() <= NumericLimits::max()); return { static_cast(m_identifiers.size() - 1) }; } -DeprecatedFlyString const& IdentifierTable::get(IdentifierTableIndex index) const +FlyString const& IdentifierTable::get(IdentifierTableIndex index) const { return m_identifiers[index.value]; } diff --git a/Libraries/LibJS/Bytecode/IdentifierTable.h b/Libraries/LibJS/Bytecode/IdentifierTable.h index e045d08f965..84501d3ae63 100644 --- a/Libraries/LibJS/Bytecode/IdentifierTable.h +++ b/Libraries/LibJS/Bytecode/IdentifierTable.h @@ -6,8 +6,8 @@ #pragma once -#include #include +#include #include namespace JS::Bytecode { @@ -24,13 +24,13 @@ class IdentifierTable { public: IdentifierTable() = default; - IdentifierTableIndex insert(DeprecatedFlyString); - DeprecatedFlyString const& get(IdentifierTableIndex) const; + IdentifierTableIndex insert(FlyString); + FlyString const& get(IdentifierTableIndex) const; void dump() const; bool is_empty() const { return m_identifiers.is_empty(); } private: - Vector m_identifiers; + Vector m_identifiers; }; } diff --git a/Libraries/LibJS/Bytecode/Interpreter.cpp b/Libraries/LibJS/Bytecode/Interpreter.cpp index 347c3cd7869..d45d84699e5 100644 --- a/Libraries/LibJS/Bytecode/Interpreter.cpp +++ b/Libraries/LibJS/Bytecode/Interpreter.cpp @@ -833,7 +833,7 @@ void Interpreter::enter_object_environment(Object& object) running_execution_context().lexical_environment = new_object_environment(object, true, old_environment); } -ThrowCompletionOr> compile(VM& vm, ASTNode const& node, FunctionKind kind, DeprecatedFlyString const& name) +ThrowCompletionOr> compile(VM& vm, ASTNode const& node, FunctionKind kind, FlyString const& name) { auto executable_result = Bytecode::Generator::generate_from_ast_node(vm, node, kind); if (executable_result.is_error()) @@ -1199,7 +1199,7 @@ inline ThrowCompletionOr get_global(Interpreter& interpreter, IdentifierT return vm.throw_completion(ErrorType::UnknownIdentifier, identifier); } -inline ThrowCompletionOr put_by_property_key(VM& vm, Value base, Value this_value, Value value, Optional const& base_identifier, PropertyKey name, Op::PropertyKind kind, PropertyLookupCache* cache = nullptr) +inline ThrowCompletionOr put_by_property_key(VM& vm, Value base, Value this_value, Value value, Optional const& base_identifier, PropertyKey name, Op::PropertyKind kind, PropertyLookupCache* cache = nullptr) { // Better error message than to_object would give if (vm.in_strict_mode() && base.is_nullish()) @@ -1219,14 +1219,14 @@ inline ThrowCompletionOr put_by_property_key(VM& vm, Value base, Value thi case Op::PropertyKind::Getter: { auto& function = value.as_function(); if (function.name().is_empty() && is(function)) - static_cast(&function)->set_name(ByteString::formatted("get {}", name)); + static_cast(&function)->set_name(MUST(String::formatted("get {}", name))); object->define_direct_accessor(name, &function, nullptr, Attribute::Configurable | Attribute::Enumerable); break; } case Op::PropertyKind::Setter: { auto& function = value.as_function(); if (function.name().is_empty() && is(function)) - static_cast(&function)->set_name(ByteString::formatted("set {}", name)); + static_cast(&function)->set_name(MUST(String::formatted("set {}", name))); object->define_direct_accessor(name, nullptr, &function, Attribute::Configurable | Attribute::Enumerable); break; } @@ -1306,7 +1306,7 @@ inline Value new_function(VM& vm, FunctionNode const& function_node, Optional put_by_value(VM& vm, Value base, Optional const& base_identifier, Value property_key_value, Value value, Op::PropertyKind kind) +inline ThrowCompletionOr put_by_value(VM& vm, Value base, Optional const& base_identifier, Value property_key_value, Value value, Op::PropertyKind kind) { // OPTIMIZATION: Fast path for simple Int32 indexes in array-like objects. if ((kind == Op::PropertyKind::KeyValue || kind == Op::PropertyKind::DirectKeyValue) @@ -1426,7 +1426,7 @@ struct CalleeAndThis { Value this_value; }; -inline ThrowCompletionOr get_callee_and_this_from_environment(Bytecode::Interpreter& interpreter, DeprecatedFlyString const& name, EnvironmentCoordinate& cache) +inline ThrowCompletionOr get_callee_and_this_from_environment(Bytecode::Interpreter& interpreter, FlyString const& name, EnvironmentCoordinate& cache) { auto& vm = interpreter.vm(); @@ -1472,14 +1472,14 @@ inline ThrowCompletionOr get_callee_and_this_from_environment(Byt } // 13.2.7.3 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-regular-expression-literals-runtime-semantics-evaluation -inline Value new_regexp(VM& vm, ParsedRegex const& parsed_regex, ByteString const& pattern, ByteString const& flags) +inline Value new_regexp(VM& vm, ParsedRegex const& parsed_regex, String const& pattern, String const& flags) { // 1. Let pattern be CodePointsToString(BodyText of RegularExpressionLiteral). // 2. Let flags be CodePointsToString(FlagText of RegularExpressionLiteral). // 3. Return ! RegExpCreate(pattern, flags). auto& realm = *vm.current_realm(); - Regex regex(parsed_regex.regex, parsed_regex.pattern, parsed_regex.flags); + Regex regex(parsed_regex.regex, parsed_regex.pattern.to_byte_string(), parsed_regex.flags); // NOTE: We bypass RegExpCreate and subsequently RegExpAlloc as an optimization to use the already parsed values. auto regexp_object = RegExpObject::create(realm, move(regex), pattern, flags); // RegExpAlloc has these two steps from the 'Legacy RegExp features' proposal. @@ -1514,7 +1514,7 @@ inline GC::RootVector argument_list_evaluation(VM& vm, Value arguments) return argument_values; } -inline ThrowCompletionOr create_variable(VM& vm, DeprecatedFlyString const& name, Op::EnvironmentMode mode, bool is_global, bool is_immutable, bool is_strict) +inline ThrowCompletionOr create_variable(VM& vm, FlyString const& name, Op::EnvironmentMode mode, bool is_global, bool is_immutable, bool is_strict) { if (mode == Op::EnvironmentMode::Lexical) { VERIFY(!is_global); @@ -1549,13 +1549,13 @@ inline ThrowCompletionOr new_class(VM& vm, Value supe auto* class_environment = vm.lexical_environment(); vm.running_execution_context().lexical_environment = vm.running_execution_context().saved_lexical_environments.take_last(); - Optional binding_name; - DeprecatedFlyString class_name; + Optional binding_name; + FlyString class_name; if (!class_expression.has_name() && lhs_name.has_value()) { class_name = interpreter.current_executable().get_identifier(lhs_name.value()); } else { binding_name = name; - class_name = name.is_null() ? ""sv : name; + class_name = name; } return TRY(class_expression.create_class_constructor(vm, class_environment, vm.lexical_environment(), super_class, element_keys, binding_name, class_name)); diff --git a/Libraries/LibJS/Bytecode/Interpreter.h b/Libraries/LibJS/Bytecode/Interpreter.h index 77f9b2cfe28..62042710c9d 100644 --- a/Libraries/LibJS/Bytecode/Interpreter.h +++ b/Libraries/LibJS/Bytecode/Interpreter.h @@ -109,7 +109,7 @@ private: extern bool g_dump_bytecode; -ThrowCompletionOr> compile(VM&, ASTNode const&, JS::FunctionKind kind, DeprecatedFlyString const& name); +ThrowCompletionOr> compile(VM&, ASTNode const&, JS::FunctionKind kind, FlyString const& name); ThrowCompletionOr> compile(VM&, ECMAScriptFunctionObject const&); } diff --git a/Libraries/LibJS/Bytecode/RegexTable.h b/Libraries/LibJS/Bytecode/RegexTable.h index 5f413d651c3..39cf635da0b 100644 --- a/Libraries/LibJS/Bytecode/RegexTable.h +++ b/Libraries/LibJS/Bytecode/RegexTable.h @@ -6,8 +6,8 @@ #pragma once -#include #include +#include #include #include @@ -17,7 +17,7 @@ AK_TYPEDEF_DISTINCT_NUMERIC_GENERAL(size_t, RegexTableIndex, Comparison); struct ParsedRegex { regex::Parser::Result regex; - ByteString pattern; + String pattern; regex::RegexOptions flags; }; diff --git a/Libraries/LibJS/Bytecode/StringTable.cpp b/Libraries/LibJS/Bytecode/StringTable.cpp index a989408ff86..c9ff83d4b77 100644 --- a/Libraries/LibJS/Bytecode/StringTable.cpp +++ b/Libraries/LibJS/Bytecode/StringTable.cpp @@ -8,13 +8,13 @@ namespace JS::Bytecode { -StringTableIndex StringTable::insert(ByteString string) +StringTableIndex StringTable::insert(String string) { m_strings.append(move(string)); return m_strings.size() - 1; } -ByteString const& StringTable::get(StringTableIndex index) const +String const& StringTable::get(StringTableIndex index) const { return m_strings[index.value()]; } diff --git a/Libraries/LibJS/Bytecode/StringTable.h b/Libraries/LibJS/Bytecode/StringTable.h index 3ff3e4e5ba8..67adf602816 100644 --- a/Libraries/LibJS/Bytecode/StringTable.h +++ b/Libraries/LibJS/Bytecode/StringTable.h @@ -6,8 +6,8 @@ #pragma once -#include #include +#include #include namespace JS::Bytecode { @@ -21,13 +21,13 @@ class StringTable { public: StringTable() = default; - StringTableIndex insert(ByteString); - ByteString const& get(StringTableIndex) const; + StringTableIndex insert(String); + String const& get(StringTableIndex) const; void dump() const; bool is_empty() const { return m_strings.is_empty(); } private: - Vector m_strings; + Vector m_strings; }; } diff --git a/Libraries/LibJS/Console.cpp b/Libraries/LibJS/Console.cpp index 1327ee1bb22..44468a45e76 100644 --- a/Libraries/LibJS/Console.cpp +++ b/Libraries/LibJS/Console.cpp @@ -172,7 +172,7 @@ static ThrowCompletionOr> create_table_row(Realm& realm, Value r // 2. Set `row["(index)"]` to `rowIndex` { - auto key = PropertyKey { "(index)", PropertyKey::StringMayBeNumber::No }; + auto key = PropertyKey { "(index)"_fly_string, PropertyKey::StringMayBeNumber::No }; TRY(row->set(key, row_index, Object::ShouldThrowExceptions::No)); add_column(key); diff --git a/Libraries/LibJS/Contrib/Test262/IsHTMLDDA.cpp b/Libraries/LibJS/Contrib/Test262/IsHTMLDDA.cpp index 9e860138d32..a6ba88506d5 100644 --- a/Libraries/LibJS/Contrib/Test262/IsHTMLDDA.cpp +++ b/Libraries/LibJS/Contrib/Test262/IsHTMLDDA.cpp @@ -13,7 +13,7 @@ GC_DEFINE_ALLOCATOR(IsHTMLDDA); IsHTMLDDA::IsHTMLDDA(Realm& realm) // NativeFunction without prototype is currently not possible (only due to the lack of a ctor that supports it) - : NativeFunction("IsHTMLDDA", realm.intrinsics().function_prototype()) + : NativeFunction("IsHTMLDDA"_fly_string, realm.intrinsics().function_prototype()) { } diff --git a/Libraries/LibJS/Lexer.cpp b/Libraries/LibJS/Lexer.cpp index 58717cee259..10f0a50477a 100644 --- a/Libraries/LibJS/Lexer.cpp +++ b/Libraries/LibJS/Lexer.cpp @@ -16,7 +16,7 @@ namespace JS { -HashMap Lexer::s_keywords; +HashMap Lexer::s_keywords; static constexpr TokenType parse_two_char_token(StringView view) { @@ -231,46 +231,46 @@ Lexer::Lexer(StringView source, StringView filename, size_t line_number, size_t , m_parsed_identifiers(adopt_ref(*new ParsedIdentifiers)) { if (s_keywords.is_empty()) { - s_keywords.set("async", TokenType::Async); - s_keywords.set("await", TokenType::Await); - s_keywords.set("break", TokenType::Break); - s_keywords.set("case", TokenType::Case); - s_keywords.set("catch", TokenType::Catch); - s_keywords.set("class", TokenType::Class); - s_keywords.set("const", TokenType::Const); - s_keywords.set("continue", TokenType::Continue); - s_keywords.set("debugger", TokenType::Debugger); - s_keywords.set("default", TokenType::Default); - s_keywords.set("delete", TokenType::Delete); - s_keywords.set("do", TokenType::Do); - s_keywords.set("else", TokenType::Else); - s_keywords.set("enum", TokenType::Enum); - s_keywords.set("export", TokenType::Export); - s_keywords.set("extends", TokenType::Extends); - s_keywords.set("false", TokenType::BoolLiteral); - s_keywords.set("finally", TokenType::Finally); - s_keywords.set("for", TokenType::For); - s_keywords.set("function", TokenType::Function); - s_keywords.set("if", TokenType::If); - s_keywords.set("import", TokenType::Import); - s_keywords.set("in", TokenType::In); - s_keywords.set("instanceof", TokenType::Instanceof); - s_keywords.set("let", TokenType::Let); - s_keywords.set("new", TokenType::New); - s_keywords.set("null", TokenType::NullLiteral); - s_keywords.set("return", TokenType::Return); - s_keywords.set("super", TokenType::Super); - s_keywords.set("switch", TokenType::Switch); - s_keywords.set("this", TokenType::This); - s_keywords.set("throw", TokenType::Throw); - s_keywords.set("true", TokenType::BoolLiteral); - s_keywords.set("try", TokenType::Try); - s_keywords.set("typeof", TokenType::Typeof); - s_keywords.set("var", TokenType::Var); - s_keywords.set("void", TokenType::Void); - s_keywords.set("while", TokenType::While); - s_keywords.set("with", TokenType::With); - s_keywords.set("yield", TokenType::Yield); + s_keywords.set("async"_fly_string, TokenType::Async); + s_keywords.set("await"_fly_string, TokenType::Await); + s_keywords.set("break"_fly_string, TokenType::Break); + s_keywords.set("case"_fly_string, TokenType::Case); + s_keywords.set("catch"_fly_string, TokenType::Catch); + s_keywords.set("class"_fly_string, TokenType::Class); + s_keywords.set("const"_fly_string, TokenType::Const); + s_keywords.set("continue"_fly_string, TokenType::Continue); + s_keywords.set("debugger"_fly_string, TokenType::Debugger); + s_keywords.set("default"_fly_string, TokenType::Default); + s_keywords.set("delete"_fly_string, TokenType::Delete); + s_keywords.set("do"_fly_string, TokenType::Do); + s_keywords.set("else"_fly_string, TokenType::Else); + s_keywords.set("enum"_fly_string, TokenType::Enum); + s_keywords.set("export"_fly_string, TokenType::Export); + s_keywords.set("extends"_fly_string, TokenType::Extends); + s_keywords.set("false"_fly_string, TokenType::BoolLiteral); + s_keywords.set("finally"_fly_string, TokenType::Finally); + s_keywords.set("for"_fly_string, TokenType::For); + s_keywords.set("function"_fly_string, TokenType::Function); + s_keywords.set("if"_fly_string, TokenType::If); + s_keywords.set("import"_fly_string, TokenType::Import); + s_keywords.set("in"_fly_string, TokenType::In); + s_keywords.set("instanceof"_fly_string, TokenType::Instanceof); + s_keywords.set("let"_fly_string, TokenType::Let); + s_keywords.set("new"_fly_string, TokenType::New); + s_keywords.set("null"_fly_string, TokenType::NullLiteral); + s_keywords.set("return"_fly_string, TokenType::Return); + s_keywords.set("super"_fly_string, TokenType::Super); + s_keywords.set("switch"_fly_string, TokenType::Switch); + s_keywords.set("this"_fly_string, TokenType::This); + s_keywords.set("throw"_fly_string, TokenType::Throw); + s_keywords.set("true"_fly_string, TokenType::BoolLiteral); + s_keywords.set("try"_fly_string, TokenType::Try); + s_keywords.set("typeof"_fly_string, TokenType::Typeof); + s_keywords.set("var"_fly_string, TokenType::Var); + s_keywords.set("void"_fly_string, TokenType::Void); + s_keywords.set("while"_fly_string, TokenType::While); + s_keywords.set("with"_fly_string, TokenType::With); + s_keywords.set("yield"_fly_string, TokenType::Yield); } consume(); @@ -699,7 +699,7 @@ Token Lexer::next() // bunch of Invalid* tokens (bad numeric literals, unterminated comments etc.) StringView token_message; - Optional identifier; + Optional identifier; size_t identifier_length = 0; if (m_current_token.type() == TokenType::RegexLiteral && !is_eof() && is_ascii_alpha(m_current_char) && !did_consume_whitespace_or_comments) { @@ -767,7 +767,7 @@ Token Lexer::next() code_point = is_identifier_middle(identifier_length); } while (code_point.has_value()); - identifier = builder.string_view(); + identifier = builder.to_string_without_validation(); token_type = TokenType::PrivateIdentifier; m_parsed_identifiers->identifiers.set(*identifier); @@ -789,7 +789,7 @@ Token Lexer::next() code_point = is_identifier_middle(identifier_length); } while (code_point.has_value()); - identifier = builder.string_view(); + identifier = builder.to_string_without_validation(); m_parsed_identifiers->identifiers.set(*identifier); auto it = s_keywords.find(identifier->hash(), [&](auto& entry) { return entry.key == identifier; }); diff --git a/Libraries/LibJS/Lexer.h b/Libraries/LibJS/Lexer.h index 7f0df05c693..052e7910bc3 100644 --- a/Libraries/LibJS/Lexer.h +++ b/Libraries/LibJS/Lexer.h @@ -80,12 +80,12 @@ private: Optional m_hit_invalid_unicode; - static HashMap s_keywords; + static HashMap s_keywords; struct ParsedIdentifiers : public RefCounted { // Resolved identifiers must be kept alive for the duration of the parsing stage, otherwise // the only references to these strings are deleted by the Token destructor. - HashTable identifiers; + HashTable identifiers; }; RefPtr m_parsed_identifiers; diff --git a/Libraries/LibJS/Module.cpp b/Libraries/LibJS/Module.cpp index 3738c490339..1e74ed84097 100644 --- a/Libraries/LibJS/Module.cpp +++ b/Libraries/LibJS/Module.cpp @@ -101,7 +101,7 @@ void finish_loading_imported_module(ImportedModuleReferrer referrer, ModuleReque // i. Append the Record { [[Specifier]]: specifier, [[Module]]: result.[[Value]] } to referrer.[[LoadedModules]]. loaded_modules.append(ModuleWithSpecifier { - .specifier = module_request.module_specifier, + .specifier = module_request.module_specifier.to_string(), .module = GC::Ref(*module) }); } } @@ -136,7 +136,7 @@ ThrowCompletionOr Module::get_module_namespace(VM& vm) auto exported_names = TRY(get_exported_names(vm)); // b. Let unambiguousNames be a new empty List. - Vector unambiguous_names; + Vector unambiguous_names; // c. For each element name of exportedNames, do for (auto& name : exported_names) { @@ -159,7 +159,7 @@ ThrowCompletionOr Module::get_module_namespace(VM& vm) } // 10.4.6.12 ModuleNamespaceCreate ( module, exports ), https://tc39.es/ecma262/#sec-modulenamespacecreate -Object* Module::module_namespace_create(Vector unambiguous_names) +Object* Module::module_namespace_create(Vector unambiguous_names) { auto& realm = this->realm(); diff --git a/Libraries/LibJS/Module.h b/Libraries/LibJS/Module.h index 8aa3da256bf..e5215f8d468 100644 --- a/Libraries/LibJS/Module.h +++ b/Libraries/LibJS/Module.h @@ -7,7 +7,7 @@ #pragma once -#include +#include #include #include #include @@ -38,7 +38,7 @@ struct ResolvedBinding { Type type { Null }; GC::Ptr module; - DeprecatedFlyString export_name; + FlyString export_name; bool is_valid() const { @@ -109,8 +109,8 @@ public: virtual ThrowCompletionOr link(VM& vm) = 0; virtual ThrowCompletionOr evaluate(VM& vm) = 0; - virtual ThrowCompletionOr> get_exported_names(VM& vm, Vector export_star_set = {}) = 0; - virtual ThrowCompletionOr resolve_export(VM& vm, DeprecatedFlyString const& export_name, Vector resolve_set = {}) = 0; + virtual ThrowCompletionOr> get_exported_names(VM& vm, Vector export_star_set = {}) = 0; + virtual ThrowCompletionOr resolve_export(VM& vm, FlyString const& export_name, Vector resolve_set = {}) = 0; virtual ThrowCompletionOr inner_module_linking(VM& vm, Vector& stack, u32 index); virtual ThrowCompletionOr inner_module_evaluation(VM& vm, Vector& stack, u32 index); @@ -128,7 +128,7 @@ protected: } private: - Object* module_namespace_create(Vector unambiguous_names); + Object* module_namespace_create(Vector unambiguous_names); // These handles are only safe as long as the VM they live in is valid. // But evaluated modules SHOULD be stored in the VM so unless you intentionally diff --git a/Libraries/LibJS/Parser.cpp b/Libraries/LibJS/Parser.cpp index 19d732079aa..161d0cc4fb3 100644 --- a/Libraries/LibJS/Parser.cpp +++ b/Libraries/LibJS/Parser.cpp @@ -105,7 +105,7 @@ public: return scope_pusher; } - static ScopePusher catch_scope(Parser& parser, RefPtr const& pattern, DeprecatedFlyString const& parameter) + static ScopePusher catch_scope(Parser& parser, RefPtr const& pattern, FlyString const& parameter) { ScopePusher scope_pusher(parser, nullptr, ScopeLevel::NotTopLevel, ScopeType::Catch); if (pattern) { @@ -233,7 +233,7 @@ public: ScopePusher* parent_scope() { return m_parent_scope; } ScopePusher const* parent_scope() const { return m_parent_scope; } - [[nodiscard]] bool has_declaration(DeprecatedFlyString const& name) const + [[nodiscard]] bool has_declaration(FlyString const& name) const { return m_lexical_names.contains(name) || m_var_names.contains(name) || !m_functions_to_hoist.find_if([&name](auto& function) { return function->name() == name; }).is_end(); } @@ -478,9 +478,9 @@ public: } private: - void throw_identifier_declared(DeprecatedFlyString const& name, NonnullRefPtr const& declaration) + void throw_identifier_declared(FlyString const& name, NonnullRefPtr const& declaration) { - m_parser.syntax_error(ByteString::formatted("Identifier '{}' already declared", name), declaration->source_range().start); + m_parser.syntax_error(MUST(String::formatted("Identifier '{}' already declared", name)), declaration->source_range().start); } Parser& m_parser; @@ -491,16 +491,16 @@ private: ScopePusher* m_parent_scope { nullptr }; ScopePusher* m_top_level_scope { nullptr }; - HashTable m_lexical_names; - HashTable m_var_names; - HashTable m_function_names; + HashTable m_lexical_names; + HashTable m_var_names; + HashTable m_function_names; - HashTable m_forbidden_lexical_names; - HashTable m_forbidden_var_names; + HashTable m_forbidden_lexical_names; + HashTable m_forbidden_var_names; Vector> m_functions_to_hoist; - HashTable m_bound_names; - HashTable m_function_parameters_candidates_for_local_variables; + HashTable m_bound_names; + HashTable m_function_parameters_candidates_for_local_variables; struct IdentifierGroup { bool captured_by_nested_function { false }; @@ -510,7 +510,7 @@ private: Vector> identifiers; Optional declaration_kind; }; - HashMap m_identifier_groups; + HashMap m_identifier_groups; Optional> m_function_parameters; @@ -736,7 +736,7 @@ bool Parser::parse_directive(ScopeNode& body) found_use_strict = true; if (m_state.string_legacy_octal_escape_sequence_in_scope) - syntax_error("Octal escape sequence in string literal not allowed in strict mode"); + syntax_error("Octal escape sequence in string literal not allowed in strict mode"_string); break; } } @@ -840,7 +840,7 @@ void Parser::parse_module(Program& program) } if (!found) - syntax_error(ByteString::formatted("'{}' in export is not declared", exported_name), export_statement->source_range().start); + syntax_error(MUST(String::formatted("'{}' in export is not declared", exported_name)), export_statement->source_range().start); } } } @@ -861,7 +861,7 @@ NonnullRefPtr Parser::parse_declaration() case TokenType::Identifier: if (m_state.current_token.original_value() == "using"sv) { if (!m_state.current_scope_pusher->can_have_using_declaration()) - syntax_error("'using' not allowed outside of block, for loop or function"); + syntax_error("'using' not allowed outside of block, for loop or function"_string); return parse_using_declaration(); } @@ -907,7 +907,7 @@ NonnullRefPtr Parser::parse_statement(AllowLabelledFunction all return parse_while_statement(); case TokenType::With: if (m_state.strict_mode) - syntax_error("'with' statement not allowed in strict mode"); + syntax_error("'with' statement not allowed in strict mode"_string); return parse_with_statement(); case TokenType::Debugger: return parse_debugger_statement(); @@ -920,7 +920,7 @@ NonnullRefPtr Parser::parse_statement(AllowLabelledFunction all [[fallthrough]]; default: if (match_invalid_escaped_keyword()) - syntax_error("Keyword must not contain escaped characters"); + syntax_error("Keyword must not contain escaped characters"_string); if (match_identifier_name()) { auto result = try_parse_labelled_statement(allow_labelled_function); @@ -931,11 +931,11 @@ NonnullRefPtr Parser::parse_statement(AllowLabelledFunction all if (match(TokenType::Async)) { auto lookahead_token = next_token(); if (lookahead_token.type() == TokenType::Function && !lookahead_token.trivia_contains_line_terminator()) - syntax_error("Async function declaration not allowed in single-statement context"); + syntax_error("Async function declaration not allowed in single-statement context"_string); } else if (match(TokenType::Function) || match(TokenType::Class)) { - syntax_error(ByteString::formatted("{} declaration not allowed in single-statement context", m_state.current_token.name())); + syntax_error(MUST(String::formatted("{} declaration not allowed in single-statement context", m_state.current_token.name()))); } else if (match(TokenType::Let) && next_token().type() == TokenType::BracketOpen) { - syntax_error(ByteString::formatted("let followed by [ is not allowed in single-statement context")); + syntax_error(MUST(String::formatted("let followed by [ is not allowed in single-statement context"))); } auto expr = parse_expression(0); @@ -1045,7 +1045,7 @@ RefPtr Parser::try_parse_arrow_function_expression(boo TemporaryChange in_async_context(m_state.await_expression_is_valid, is_async || m_state.await_expression_is_valid); parameters = parse_formal_parameters(function_length, FunctionNodeParseOptions::IsArrowFunction | (is_async ? FunctionNodeParseOptions::IsAsyncFunction : 0)); - if (m_state.errors.size() > previous_syntax_errors && m_state.errors[previous_syntax_errors].message.starts_with("Unexpected token"sv)) + if (m_state.errors.size() > previous_syntax_errors && m_state.errors[previous_syntax_errors].message.bytes_as_string_view().starts_with("Unexpected token"sv)) return nullptr; if (!match(TokenType::ParenClose)) return nullptr; @@ -1056,10 +1056,10 @@ RefPtr Parser::try_parse_arrow_function_expression(boo return nullptr; auto token = consume_identifier_reference(); if (m_state.strict_mode && token.value().is_one_of("arguments"sv, "eval"sv)) - syntax_error("BindingIdentifier may not be 'arguments' or 'eval' in strict mode"); + syntax_error("BindingIdentifier may not be 'arguments' or 'eval' in strict mode"_string); if (is_async && token.value() == "await"sv) - syntax_error("'await' is a reserved identifier in async functions"); - auto identifier = create_ast_node({ m_source_code, rule_start.position(), position() }, token.DeprecatedFlyString_value()); + syntax_error("'await' is a reserved identifier in async functions"_string); + auto identifier = create_ast_node({ m_source_code, rule_start.position(), position() }, token.fly_string_value()); parameters.append({ identifier, {} }); } // If there's a newline between the closing paren and arrow it's not a valid arrow function, @@ -1164,9 +1164,9 @@ RefPtr Parser::try_parse_labelled_statement(AllowLabell auto identifier = [&] { if (m_state.current_token.value() == "await"sv) { - return consume().value(); + return consume().fly_string_value(); } - return consume_identifier_reference().value(); + return consume_identifier_reference().fly_string_value(); }(); if (!match(TokenType::Colon)) return {}; @@ -1179,17 +1179,17 @@ RefPtr Parser::try_parse_labelled_statement(AllowLabell discard_saved_state(); if (m_state.strict_mode && identifier == "let"sv) { - syntax_error("Strict mode reserved word 'let' is not allowed in label", rule_start.position()); + syntax_error("Strict mode reserved word 'let' is not allowed in label"_string, rule_start.position()); return {}; } if (match(TokenType::Function) && (allow_function == AllowLabelledFunction::No || m_state.strict_mode)) { - syntax_error("Not allowed to declare a function here"); + syntax_error("Not allowed to declare a function here"_string); return {}; } if (m_state.labels_in_scope.contains(identifier)) - syntax_error(ByteString::formatted("Label '{}' has already been declared", identifier)); + syntax_error(MUST(String::formatted("Label '{}' has already been declared", identifier))); RefPtr labelled_item; @@ -1201,9 +1201,9 @@ RefPtr Parser::try_parse_labelled_statement(AllowLabell VERIFY(m_state.current_scope_pusher); m_state.current_scope_pusher->add_declaration(function_declaration); if (function_declaration->kind() == FunctionKind::Generator) - syntax_error("Generator functions cannot be defined in labelled statements"); + syntax_error("Generator functions cannot be defined in labelled statements"_string); if (function_declaration->kind() == FunctionKind::Async) - syntax_error("Async functions cannot be defined in labelled statements"); + syntax_error("Async functions cannot be defined in labelled statements"_string); labelled_item = move(function_declaration); } else { @@ -1219,7 +1219,7 @@ RefPtr Parser::try_parse_labelled_statement(AllowLabell if (!is_iteration_statement) { if (auto entry = m_state.labels_in_scope.find(identifier); entry != m_state.labels_in_scope.end() && entry->value.has_value()) - syntax_error("labelled continue statement cannot use non iterating statement", m_state.labels_in_scope.get(identifier).value()); + syntax_error("labelled continue statement cannot use non iterating statement"_string, m_state.labels_in_scope.get(identifier).value()); } m_state.labels_in_scope.remove(identifier); @@ -1330,11 +1330,11 @@ NonnullRefPtr Parser::parse_class_expression(bool expect_ Vector> elements; RefPtr super_class; RefPtr constructor; - HashTable found_private_names; + HashTable found_private_names; RefPtr class_name; if (expect_class_name || match_identifier() || match(TokenType::Yield) || match(TokenType::Await)) { - class_name = create_identifier_and_register_in_current_scope({ m_source_code, rule_start.position(), position() }, consume_identifier_reference().DeprecatedFlyString_value()); + class_name = create_identifier_and_register_in_current_scope({ m_source_code, rule_start.position(), position() }, consume_identifier_reference().fly_string_value()); } ScopePusher class_declaration_scope = ScopePusher::class_declaration_scope(*this, class_name); @@ -1342,7 +1342,7 @@ NonnullRefPtr Parser::parse_class_expression(bool expect_ if (class_name) check_identifier_name_for_assignment_validity(class_name->string(), true); if (m_state.in_class_static_init_block && class_name && class_name->string() == "await"sv) - syntax_error("Identifier must not be a reserved word in modules ('await')"); + syntax_error("Identifier must not be a reserved word in modules ('await')"_string); if (match(TokenType::Extends)) { consume(); @@ -1369,8 +1369,8 @@ NonnullRefPtr Parser::parse_class_expression(bool expect_ consume(TokenType::CurlyOpen); - HashTable referenced_private_names; - HashTable* outer_referenced_private_names = m_state.referenced_private_names; + HashTable referenced_private_names; + HashTable* outer_referenced_private_names = m_state.referenced_private_names; m_state.referenced_private_names = &referenced_private_names; ScopeGuard restore_private_name_table = [&] { m_state.referenced_private_names = outer_referenced_private_names; @@ -1407,7 +1407,7 @@ NonnullRefPtr Parser::parse_class_expression(bool expect_ is_generator = true; } - StringView name; + FlyString name; if (match_property_key() || match(TokenType::PrivateIdentifier)) { if (!is_generator && !is_async && m_state.current_token.original_value() == "static"sv) { if (match(TokenType::Identifier)) { @@ -1440,13 +1440,13 @@ NonnullRefPtr Parser::parse_class_expression(bool expect_ if (match_property_key() || match(TokenType::PrivateIdentifier)) { switch (m_state.current_token.type()) { case TokenType::Identifier: - name = consume().value(); - property_key = create_ast_node({ m_source_code, rule_start.position(), position() }, name); + name = consume().fly_string_value(); + property_key = create_ast_node({ m_source_code, rule_start.position(), position() }, name.to_string()); break; case TokenType::PrivateIdentifier: - name = consume().value(); + name = consume().fly_string_value(); if (name == "#constructor") - syntax_error("Private property with name '#constructor' is not allowed"); + syntax_error("Private property with name '#constructor' is not allowed"_string); if (method_kind != ClassMethod::Kind::Method) { // It is a Syntax Error if PrivateBoundIdentifiers of ClassElementList contains any duplicate entries, @@ -1460,7 +1460,7 @@ NonnullRefPtr Parser::parse_class_expression(bool expect_ if (element->class_element_kind() != ClassElement::ElementKind::Method || element->is_static() != is_static) { - syntax_error(ByteString::formatted("Duplicate private field or method named '{}'", name)); + syntax_error(MUST(String::formatted("Duplicate private field or method named '{}'", name))); break; } @@ -1468,14 +1468,14 @@ NonnullRefPtr Parser::parse_class_expression(bool expect_ auto& class_method_element = static_cast(*element); if (class_method_element.kind() == ClassMethod::Kind::Method || class_method_element.kind() == method_kind) { - syntax_error(ByteString::formatted("Duplicate private field or method named '{}'", name)); + syntax_error(MUST(String::formatted("Duplicate private field or method named '{}'", name))); break; } } found_private_names.set(name); } else if (found_private_names.set(name) != AK::HashSetResult::InsertedNewEntry) { - syntax_error(ByteString::formatted("Duplicate private field or method named '{}'", name)); + syntax_error(MUST(String::formatted("Duplicate private field or method named '{}'", name))); } property_key = create_ast_node({ m_source_code, rule_start.position(), position() }, name); @@ -1495,29 +1495,29 @@ NonnullRefPtr Parser::parse_class_expression(bool expect_ // ClassElement : static MethodDefinition // It is a Syntax Error if PropName of MethodDefinition is "prototype". if (is_static && name == "prototype"sv) - syntax_error("Classes may not have a static property named 'prototype'"); + syntax_error("Classes may not have a static property named 'prototype'"_string); } else if ((match(TokenType::ParenOpen) || match(TokenType::Equals) || match(TokenType::Semicolon) || match(TokenType::CurlyClose)) && (is_static || is_async || method_kind != ClassMethod::Kind::Method)) { switch (method_kind) { case ClassMethod::Kind::Method: if (is_async) { - name = "async"sv; + name = "async"_fly_string; is_async = false; } else { VERIFY(is_static); - name = "static"sv; + name = "static"_fly_string; is_static = false; } break; case ClassMethod::Kind::Getter: - name = "get"sv; + name = "get"_fly_string; method_kind = ClassMethod::Kind::Method; break; case ClassMethod::Kind::Setter: - name = "set"sv; + name = "set"_fly_string; method_kind = ClassMethod::Kind::Method; break; } - property_key = create_ast_node({ m_source_code, rule_start.position(), position() }, name); + property_key = create_ast_node({ m_source_code, rule_start.position(), position() }, name.to_string()); } else if (match(TokenType::CurlyOpen) && is_static) { auto static_start = push_start(); consume(TokenType::CurlyOpen); @@ -1546,13 +1546,13 @@ NonnullRefPtr Parser::parse_class_expression(bool expect_ // Constructor may be a StringLiteral or an Identifier. if (!is_static && name == "constructor"sv) { if (method_kind != ClassMethod::Kind::Method) - syntax_error("Class constructor may not be an accessor"); + syntax_error("Class constructor may not be an accessor"_string); if (!constructor.is_null()) - syntax_error("Classes may not have more than one constructor"); + syntax_error("Classes may not have more than one constructor"_string); if (is_generator) - syntax_error("Class constructor may not be a generator"); + syntax_error("Class constructor may not be a generator"_string); if (is_async) - syntax_error("Class constructor may not be async"); + syntax_error("Class constructor may not be async"_string); is_constructor = true; } @@ -1576,7 +1576,7 @@ NonnullRefPtr Parser::parse_class_expression(bool expect_ } else if (!property_key.is_null()) { elements.append(create_ast_node({ m_source_code, rule_start.position(), position() }, property_key.release_nonnull(), move(function), method_kind, is_static)); } else { - syntax_error("No key for class method"); + syntax_error("No key for class method"_string); } } else if (is_generator || is_async) { expected("ParenOpen"); @@ -1586,7 +1586,7 @@ NonnullRefPtr Parser::parse_class_expression(bool expect_ consume(); } else { if (name == "constructor"sv) - syntax_error("Class cannot have field named 'constructor'"); + syntax_error("Class cannot have field named 'constructor'"_string); RefPtr initializer; bool contains_direct_call_to_eval = false; @@ -1620,11 +1620,11 @@ NonnullRefPtr Parser::parse_class_expression(bool expect_ // this function does not. // So we use a custom version of SuperCall which doesn't use the @@iterator // method on %Array.prototype% visibly. - auto argument_name = create_ast_node({ m_source_code, rule_start.position(), position() }, "args"); + auto argument_name = create_ast_node({ m_source_code, rule_start.position(), position() }, "args"_fly_string); auto super_call = create_ast_node( { m_source_code, rule_start.position(), position() }, SuperCall::IsPartOfSyntheticConstructor::Yes, - CallExpression::Argument { create_ast_node({ m_source_code, rule_start.position(), position() }, "args"), true }); + CallExpression::Argument { create_ast_node({ m_source_code, rule_start.position(), position() }, "args"_fly_string), true }); // NOTE: While the JS approximation above doesn't do `return super(...args)`, the // abstract closure is expected to capture and return the result, so we do need a // return statement here to create the correct completion. @@ -1634,13 +1634,13 @@ NonnullRefPtr Parser::parse_class_expression(bool expect_ constructor = create_ast_node( { m_source_code, rule_start.position(), position() }, class_name, "", move(constructor_body), Vector { FunctionParameter { move(argument_name), nullptr, true } }, 0, FunctionKind::Normal, - /* is_strict_mode */ true, parsing_insights, /* local_variables_names */ Vector {}); + /* is_strict_mode */ true, parsing_insights, /* local_variables_names */ Vector {}); } else { FunctionParsingInsights parsing_insights; constructor = create_ast_node( { m_source_code, rule_start.position(), position() }, class_name, "", move(constructor_body), Vector {}, 0, FunctionKind::Normal, - /* is_strict_mode */ true, parsing_insights, /* local_variables_names */ Vector {}); + /* is_strict_mode */ true, parsing_insights, /* local_variables_names */ Vector {}); } } @@ -1650,8 +1650,9 @@ NonnullRefPtr Parser::parse_class_expression(bool expect_ continue; if (outer_referenced_private_names) outer_referenced_private_names->set(private_name); - else // FIXME: Make these error appear in the appropriate places. - syntax_error(ByteString::formatted("Reference to undeclared private field or method '{}'", private_name)); + else { // FIXME: Make these error appear in the appropriate places. + syntax_error(MUST(String::formatted("Reference to undeclared private field or method '{}'", private_name))); + } } auto function_start_offset = rule_start.position().offset; @@ -1694,9 +1695,9 @@ Parser::PrimaryExpressionParseResult Parser::parse_primary_expression() } else if (is(*expression)) { auto& function = static_cast(*expression); if (function.kind() == FunctionKind::Generator && function.name() == "yield"sv) - syntax_error("function is not allowed to be called 'yield' in this context", function.source_range().start); + syntax_error("function is not allowed to be called 'yield' in this context"_string, function.source_range().start); if (function.kind() == FunctionKind::Async && function.name() == "await"sv) - syntax_error("function is not allowed to be called 'await' in this context", function.source_range().start); + syntax_error("function is not allowed to be called 'await' in this context"_string, function.source_range().start); } return { move(expression) }; } @@ -1711,13 +1712,13 @@ Parser::PrimaryExpressionParseResult Parser::parse_primary_expression() case TokenType::Super: consume(); if (!m_state.allow_super_property_lookup) - syntax_error("'super' keyword unexpected here"); + syntax_error("'super' keyword unexpected here"_string); if (m_state.current_scope_pusher) m_state.current_scope_pusher->set_uses_new_target(); return { create_ast_node({ m_source_code, rule_start.position(), position() }) }; case TokenType::EscapedKeyword: if (match_invalid_escaped_keyword()) - syntax_error("Keyword must not contain escaped characters"); + syntax_error("Keyword must not contain escaped characters"_string); [[fallthrough]]; case TokenType::Identifier: { read_as_identifier:; @@ -1727,7 +1728,7 @@ Parser::PrimaryExpressionParseResult Parser::parse_primary_expression() auto string = m_state.current_token.value(); // This could be 'eval' or 'arguments' and thus needs a custom check (`eval[1] = true`) if (m_state.strict_mode && (string == "let" || is_strict_reserved_word(string))) - syntax_error(ByteString::formatted("Identifier must not be a reserved word in strict mode ('{}')", string)); + syntax_error(MUST(String::formatted("Identifier must not be a reserved word in strict mode ('{}')", string))); return { parse_identifier() }; } case TokenType::NumericLiteral: @@ -1774,7 +1775,7 @@ Parser::PrimaryExpressionParseResult Parser::parse_primary_expression() auto new_target_result = try_parse_new_target_expression(); if (!new_target_result.is_null()) { if (!m_state.in_function_context && !m_state.in_eval_function_context && !m_state.in_class_static_init_block) - syntax_error("'new.target' not allowed outside of a function", new_start); + syntax_error("'new.target' not allowed outside of a function"_string, new_start); return { new_target_result.release_nonnull() }; } return { parse_new_expression() }; @@ -1787,7 +1788,7 @@ Parser::PrimaryExpressionParseResult Parser::parse_primary_expression() if (lookahead_token.type() == TokenType::Period) { if (auto import_meta = try_parse_import_meta_expression()) { if (m_program_type != Program::Type::Module) - syntax_error("import.meta is only allowed in modules"); + syntax_error("import.meta is only allowed in modules"_string); return { import_meta.release_nonnull() }; } } else { @@ -1806,10 +1807,10 @@ Parser::PrimaryExpressionParseResult Parser::parse_primary_expression() return { parse_await_expression() }; case TokenType::PrivateIdentifier: if (!is_private_identifier_valid()) - syntax_error(ByteString::formatted("Reference to undeclared private field or method '{}'", m_state.current_token.value())); + syntax_error(MUST(String::formatted("Reference to undeclared private field or method '{}'", m_state.current_token.value()))); if (next_token().type() != TokenType::In) - syntax_error("Cannot have a private identifier in expression if not followed by 'in'"); - return { create_ast_node({ m_source_code, rule_start.position(), position() }, consume().value()) }; + syntax_error("Cannot have a private identifier in expression if not followed by 'in'"_string); + return { create_ast_node({ m_source_code, rule_start.position(), position() }, consume().fly_string_value()) }; default: if (match_identifier_name()) goto read_as_identifier; @@ -1823,16 +1824,16 @@ Parser::PrimaryExpressionParseResult Parser::parse_primary_expression() NonnullRefPtr Parser::parse_regexp_literal() { auto rule_start = push_start(); - auto pattern = consume().value(); + auto pattern = consume().fly_string_value().to_string(); // Remove leading and trailing slash. - pattern = pattern.substring_view(1, pattern.length() - 2); + pattern = MUST(pattern.substring_from_byte_offset(1, pattern.bytes().size() - 2)); - auto flags = ByteString::empty(); + auto flags = String {}; auto parsed_flags = RegExpObject::default_flags; if (match(TokenType::RegexFlags)) { auto flags_start = position(); - flags = consume().value(); + flags = consume().fly_string_value().to_string(); auto parsed_flags_or_error = regex_flags_from_string(flags); if (parsed_flags_or_error.is_error()) @@ -1841,21 +1842,21 @@ NonnullRefPtr Parser::parse_regexp_literal() parsed_flags = parsed_flags_or_error.release_value(); } - ByteString parsed_pattern; + String parsed_pattern; auto parsed_pattern_result = parse_regex_pattern(pattern, parsed_flags.has_flag_set(ECMAScriptFlags::Unicode), parsed_flags.has_flag_set(ECMAScriptFlags::UnicodeSets)); if (parsed_pattern_result.is_error()) { syntax_error(parsed_pattern_result.release_error().error, rule_start.position()); - parsed_pattern = ByteString::empty(); + parsed_pattern = ""_string; } else { parsed_pattern = parsed_pattern_result.release_value(); } auto parsed_regex = Regex::parse_pattern(parsed_pattern, parsed_flags); if (parsed_regex.error != regex::Error::NoError) - syntax_error(ByteString::formatted("RegExp compile error: {}", Regex(parsed_regex, parsed_pattern, parsed_flags).error_string()), rule_start.position()); + syntax_error(MUST(String::formatted("RegExp compile error: {}", Regex(parsed_regex, parsed_pattern.to_byte_string(), parsed_flags).error_string())), rule_start.position()); SourceRange range { m_source_code, rule_start.position(), position() }; - return create_ast_node(move(range), move(parsed_regex), move(parsed_pattern), move(parsed_flags), pattern.to_byte_string(), move(flags)); + return create_ast_node(move(range), move(parsed_regex), move(parsed_pattern), move(parsed_flags), move(pattern), move(flags)); } static bool is_simple_assignment_target(Expression const& expression, bool allow_web_reality_call_expression = true) @@ -1872,7 +1873,7 @@ NonnullRefPtr Parser::parse_unary_prefixed_expression() auto verify_next_token_is_not_exponentiation = [this]() { auto lookahead_token = next_token(); if (lookahead_token.type() == TokenType::DoubleAsterisk) - syntax_error("Unary operator must not be used before exponentiation expression without brackets"); + syntax_error("Unary operator must not be used before exponentiation expression without brackets"_string); }; switch (m_state.current_token.type()) { @@ -1881,7 +1882,7 @@ NonnullRefPtr Parser::parse_unary_prefixed_expression() auto rhs_start = position(); auto rhs = parse_expression(precedence, associativity); if (!is_simple_assignment_target(*rhs)) - syntax_error(ByteString::formatted("Right-hand side of prefix increment operator must be identifier or member expression, got {}", rhs->class_name()), rhs_start); + syntax_error(MUST(String::formatted("Right-hand side of prefix increment operator must be identifier or member expression, got {}", rhs->class_name())), rhs_start); if (m_state.strict_mode && is(*rhs)) { auto& identifier = static_cast(*rhs); @@ -1896,7 +1897,7 @@ NonnullRefPtr Parser::parse_unary_prefixed_expression() auto rhs_start = position(); auto rhs = parse_expression(precedence, associativity); if (!is_simple_assignment_target(*rhs)) - syntax_error(ByteString::formatted("Right-hand side of prefix decrement operator must be identifier or member expression, got {}", rhs->class_name()), rhs_start); + syntax_error(MUST(String::formatted("Right-hand side of prefix decrement operator must be identifier or member expression, got {}", rhs->class_name())), rhs_start); if (m_state.strict_mode && is(*rhs)) { auto& identifier = static_cast(*rhs); @@ -1931,7 +1932,7 @@ NonnullRefPtr Parser::parse_unary_prefixed_expression() verify_next_token_is_not_exponentiation(); // FIXME: This check is really hiding the fact that we don't deal with different expressions correctly. if (match(TokenType::Yield) && m_state.in_generator_function_context) - syntax_error("'yield' is not an identifier in generator function context"); + syntax_error("'yield' is not an identifier in generator function context"_string); return create_ast_node({ m_source_code, rule_start.position(), position() }, UnaryOp::Void, parse_expression(precedence, associativity)); case TokenType::Delete: { consume(); @@ -1939,12 +1940,12 @@ NonnullRefPtr Parser::parse_unary_prefixed_expression() auto rhs_start = position(); auto rhs = parse_expression(precedence, associativity); if (is(*rhs) && m_state.strict_mode) { - syntax_error("Delete of an unqualified identifier in strict mode.", rhs_start); + syntax_error("Delete of an unqualified identifier in strict mode."_string, rhs_start); } if (is(*rhs)) { auto& member_expression = static_cast(*rhs); if (member_expression.ends_in_private_name()) - syntax_error("Private fields cannot be deleted"); + syntax_error("Private fields cannot be deleted"_string); } return create_ast_node({ m_source_code, rule_start.position(), position() }, UnaryOp::Delete, move(rhs)); } @@ -1972,7 +1973,7 @@ NonnullRefPtr Parser::parse_property_key() } else { if (!match_identifier_name()) expected("IdentifierName"); - return create_ast_node({ m_source_code, rule_start.position(), position() }, consume().value()); + return create_ast_node({ m_source_code, rule_start.position(), position() }, consume().fly_string_value().to_string()); } } @@ -2040,8 +2041,8 @@ NonnullRefPtr Parser::parse_object_expression() property_type = ObjectProperty::Type::Setter; property_key = parse_property_key(); } else { - property_key = create_ast_node({ m_source_code, rule_start.position(), position() }, identifier.value()); - property_value = create_identifier_and_register_in_current_scope({ m_source_code, rule_start.position(), position() }, identifier.DeprecatedFlyString_value()); + property_key = create_ast_node({ m_source_code, rule_start.position(), position() }, identifier.fly_string_value().to_string()); + property_value = create_identifier_and_register_in_current_scope({ m_source_code, rule_start.position(), position() }, identifier.fly_string_value()); } } else { property_key = parse_property_key(); @@ -2081,7 +2082,7 @@ NonnullRefPtr Parser::parse_object_expression() properties.append(create_ast_node({ m_source_code, rule_start.position(), position() }, *property_key, function, property_type, true)); } else if (function_kind == FunctionKind::Async) { // If we previously parsed an `async` keyword, then a function must follow. - syntax_error("Expected function after async keyword"); + syntax_error("Expected function after async keyword"_string); skip_to_next_property(); continue; } else if (match(TokenType::Colon)) { @@ -2093,7 +2094,7 @@ NonnullRefPtr Parser::parse_object_expression() consume(); if (is_proto) { if (has_direct_proto_property) - syntax_error("Property name '__proto__' must not appear more than once in object literal"); + syntax_error("Property name '__proto__' must not appear more than once in object literal"_string); has_direct_proto_property = true; } if (is_proto && property_type == ObjectProperty::Type::KeyValue) @@ -2106,7 +2107,7 @@ NonnullRefPtr Parser::parse_object_expression() if (m_state.strict_mode && is(*property_key)) { auto& string_literal = static_cast(*property_key); if (is_strict_reserved_word(string_literal.value())) - syntax_error(ByteString::formatted("'{}' is a reserved keyword", string_literal.value())); + syntax_error(MUST(String::formatted("'{}' is a reserved keyword", string_literal.value()))); } properties.append(create_ast_node({ m_source_code, rule_start.position(), position() }, *property_key, *property_value, property_type, false)); @@ -2170,19 +2171,19 @@ NonnullRefPtr Parser::parse_string_literal(Token const& tok auto string = token.string_value(status); // NOTE: Tagged templates should not fail on invalid strings as their raw contents can still be accessed. if (status != Token::StringValueStatus::Ok) { - ByteString message; + String message; if (status == Token::StringValueStatus::LegacyOctalEscapeSequence) { m_state.string_legacy_octal_escape_sequence_in_scope = true; // It is a Syntax Error if the [Tagged] parameter was not set and Template{Head, Middle, Tail} Contains NotEscapeSequence. if (string_literal_type != StringLiteralType::Normal) - message = "Octal escape sequence not allowed in template literal"; + message = "Octal escape sequence not allowed in template literal"_string; else if (m_state.strict_mode) - message = "Octal escape sequence in string literal not allowed in strict mode"; + message = "Octal escape sequence in string literal not allowed in strict mode"_string; } else if (status == Token::StringValueStatus::MalformedHexEscape || status == Token::StringValueStatus::MalformedUnicodeEscape) { auto type = status == Token::StringValueStatus::MalformedUnicodeEscape ? "unicode" : "hexadecimal"; - message = ByteString::formatted("Malformed {} escape sequence", type); + message = MUST(String::formatted("Malformed {} escape sequence", type)); } else if (status == Token::StringValueStatus::UnicodeEscapeOverflow) { - message = "Unicode code_point must not be greater than 0x10ffff in escape sequence"; + message = "Unicode code_point must not be greater than 0x10ffff in escape sequence"_string; } else { VERIFY_NOT_REACHED(); } @@ -2197,7 +2198,7 @@ NonnullRefPtr Parser::parse_string_literal(Token const& tok } } - return create_ast_node({ m_source_code, rule_start.position(), position() }, string); + return create_ast_node({ m_source_code, rule_start.position(), position() }, MUST(String::from_byte_string(string))); } NonnullRefPtr Parser::parse_template_literal(bool is_tagged) @@ -2209,7 +2210,7 @@ NonnullRefPtr Parser::parse_template_literal(bool is_tagg Vector> raw_strings; auto append_empty_string = [this, &rule_start, &expressions, &raw_strings, is_tagged]() { - auto string_literal = create_ast_node({ m_source_code, rule_start.position(), position() }, ""); + auto string_literal = create_ast_node({ m_source_code, rule_start.position(), position() }, ""_string); expressions.append(string_literal); if (is_tagged) raw_strings.append(string_literal); @@ -2231,17 +2232,17 @@ NonnullRefPtr Parser::parse_template_literal(bool is_tagg else expressions.append(move(parsed_string_value)); if (is_tagged) - raw_strings.append(create_ast_node({ m_source_code, rule_start.position(), position() }, token.raw_template_value())); + raw_strings.append(create_ast_node({ m_source_code, rule_start.position(), position() }, MUST(String::from_byte_string(token.raw_template_value())))); } else if (match(TokenType::TemplateLiteralExprStart)) { consume(TokenType::TemplateLiteralExprStart); if (match(TokenType::TemplateLiteralExprEnd)) { - syntax_error("Empty template literal expression block"); + syntax_error("Empty template literal expression block"_string); return create_ast_node({ m_source_code, rule_start.position(), position() }, expressions); } expressions.append(parse_expression(0)); if (match(TokenType::UnterminatedTemplateLiteral)) { - syntax_error("Unterminated template literal"); + syntax_error("Unterminated template literal"_string); return create_ast_node({ m_source_code, rule_start.position(), position() }, expressions); } consume(TokenType::TemplateLiteralExprEnd); @@ -2255,7 +2256,7 @@ NonnullRefPtr Parser::parse_template_literal(bool is_tagg } if (match(TokenType::UnterminatedTemplateLiteral)) { - syntax_error("Unterminated template literal"); + syntax_error("Unterminated template literal"_string); } else { consume(TokenType::TemplateLiteralEnd); } @@ -2272,7 +2273,7 @@ NonnullRefPtr Parser::parse_expression(int min_precedence, Ass auto check_for_invalid_object_property = [&](auto& expression) { if (is(*expression)) { if (auto start_offset = m_state.invalid_property_range_in_object_expression.get(expression->start_offset()); start_offset.has_value()) - syntax_error("Invalid property in object literal", start_offset.value()); + syntax_error("Invalid property in object literal"_string, start_offset.value()); } }; if (is(*expression) && m_state.current_scope_pusher) { @@ -2319,7 +2320,7 @@ NonnullRefPtr Parser::parse_expression(int min_precedence, Ass } if (is(*expression)) - syntax_error("'super' keyword unexpected here"); + syntax_error("'super' keyword unexpected here"_string); check_for_invalid_object_property(expression); @@ -2446,16 +2447,16 @@ Parser::ExpressionResult Parser::parse_secondary_expression(NonnullRefPtr(*lhs)) - syntax_error(ByteString::formatted("Cannot access private field or method '{}' on super", m_state.current_token.value())); + syntax_error(MUST(String::formatted("Cannot access private field or method '{}' on super", m_state.current_token.value()))); - return create_ast_node({ m_source_code, rule_start.position(), position() }, move(lhs), create_ast_node({ m_source_code, rule_start.position(), position() }, consume().value())); + return create_ast_node({ m_source_code, rule_start.position(), position() }, move(lhs), create_ast_node({ m_source_code, rule_start.position(), position() }, consume().fly_string_value().to_string())); } else if (!match_identifier_name()) { expected("IdentifierName"); } - return create_ast_node({ m_source_code, rule_start.position(), position() }, move(lhs), create_ast_node({ m_source_code, rule_start.position(), position() }, consume_and_allow_division().DeprecatedFlyString_value())); + return create_ast_node({ m_source_code, rule_start.position(), position() }, move(lhs), create_ast_node({ m_source_code, rule_start.position(), position() }, consume_and_allow_division().fly_string_value())); case TokenType::BracketOpen: { consume(TokenType::BracketOpen); auto expression = create_ast_node({ m_source_code, rule_start.position(), position() }, move(lhs), parse_expression(0), true); @@ -2464,7 +2465,7 @@ Parser::ExpressionResult Parser::parse_secondary_expression(NonnullRefPtrclass_name())); + syntax_error(MUST(String::formatted("Left-hand side of postfix increment operator must be identifier or member expression, got {}", lhs->class_name()))); if (m_state.strict_mode && is(*lhs)) { auto& identifier = static_cast(*lhs); @@ -2476,7 +2477,7 @@ Parser::ExpressionResult Parser::parse_secondary_expression(NonnullRefPtr({ m_source_code, rule_start.position(), position() }, UpdateOp::Increment, move(lhs)); case TokenType::MinusMinus: if (!is_simple_assignment_target(*lhs)) - syntax_error(ByteString::formatted("Left-hand side of postfix increment operator must be identifier or member expression, got {}", lhs->class_name())); + syntax_error(MUST(String::formatted("Left-hand side of postfix increment operator must be identifier or member expression, got {}", lhs->class_name()))); if (m_state.strict_mode && is(*lhs)) { auto& identifier = static_cast(*lhs); @@ -2513,7 +2514,7 @@ Parser::ExpressionResult Parser::parse_secondary_expression(NonnullRefPtr(lhs_expression)) { auto const& new_expression = static_cast(*lhs_expression); if (!new_expression.is_parenthesized() && !new_expression.is_inside_parens()) { - syntax_error("'new' cannot be used with optional chaining", position()); + syntax_error("'new' cannot be used with optional chaining"_string, position()); consume(); return lhs; } @@ -2534,7 +2535,7 @@ bool Parser::is_private_identifier_valid() const return false; // We might not have hit the declaration yet so class will check this in the end - m_state.referenced_private_names->set(m_state.current_token.value()); + m_state.referenced_private_names->set(m_state.current_token.fly_string_value()); return true; } @@ -2619,7 +2620,7 @@ NonnullRefPtr Parser::parse_assignment_expression(As && assignment_op != AssignmentOp::NullishAssignment; if (!is_simple_assignment_target(*lhs, has_web_reality_assignment_target_exceptions)) { - syntax_error("Invalid left-hand side in assignment"); + syntax_error("Invalid left-hand side in assignment"_string); } else if (m_state.strict_mode && is(*lhs)) { auto const& name = static_cast(*lhs).string(); check_identifier_name_for_assignment_validity(name); @@ -2633,8 +2634,8 @@ NonnullRefPtr Parser::parse_identifier() auto identifier_start = position(); auto token = consume_identifier(); if (m_state.in_class_field_initializer && token.value() == "arguments"sv) - syntax_error("'arguments' is not allowed in class field initializer"); - return create_identifier_and_register_in_current_scope({ m_source_code, identifier_start, position() }, token.DeprecatedFlyString_value()); + syntax_error("'arguments' is not allowed in class field initializer"_string); + return create_identifier_and_register_in_current_scope({ m_source_code, identifier_start, position() }, token.fly_string_value()); } Vector Parser::parse_arguments() @@ -2662,7 +2663,7 @@ NonnullRefPtr Parser::parse_call_expression(NonnullRefPtr(*lhs)) - syntax_error("'super' keyword unexpected here"); + syntax_error("'super' keyword unexpected here"_string); auto arguments = parse_arguments(); @@ -2679,7 +2680,7 @@ NonnullRefPtr Parser::parse_new_expression() auto callee = parse_expression(g_operator_precedence.get(TokenType::New), Associativity::Right, { TokenType::ParenOpen, TokenType::QuestionMarkPeriod }); if (is(*callee)) - syntax_error("Cannot call new on dynamic import", callee->source_range().start); + syntax_error("Cannot call new on dynamic import"_string, callee->source_range().start); Vector arguments; @@ -2711,7 +2712,7 @@ NonnullRefPtr Parser::parse_yield_expression() auto rule_start = push_start(); if (m_state.in_formal_parameter_context) - syntax_error("'Yield' expression is not allowed in formal parameters of generator function"); + syntax_error("'Yield' expression is not allowed in formal parameters of generator function"_string); consume(TokenType::Yield); RefPtr argument; @@ -2735,7 +2736,7 @@ NonnullRefPtr Parser::parse_await_expression() auto rule_start = push_start(); if (m_state.in_formal_parameter_context) - syntax_error("'Await' expression is not allowed in formal parameters of an async function"); + syntax_error("'Await' expression is not allowed in formal parameters of an async function"_string); consume(TokenType::Await); @@ -2752,7 +2753,7 @@ NonnullRefPtr Parser::parse_return_statement() { auto rule_start = push_start(); if (!m_state.in_function_context && !m_state.in_arrow_function_context) - syntax_error("'return' not allowed outside of a function"); + syntax_error("'return' not allowed outside of a function"_string); consume(TokenType::Return); @@ -2804,7 +2805,7 @@ NonnullRefPtr Parser::parse_function_body(Vectorset_strict_mode(); if (!is_simple_parameter_list(parameters)) - syntax_error("Illegal 'use strict' directive in function with non-simple parameter list"); + syntax_error("Illegal 'use strict' directive in function with non-simple parameter list"_string); } else if (previous_strict_mode) { function_body->set_strict_mode(); } @@ -2826,14 +2827,14 @@ NonnullRefPtr Parser::parse_function_body(Vectorin_strict_mode()); if (function_kind == FunctionKind::Generator && parameter_name == "yield"sv) - syntax_error("Parameter name 'yield' not allowed in this context"); + syntax_error("Parameter name 'yield' not allowed in this context"_string); if (function_kind == FunctionKind::Async && parameter_name == "await"sv) - syntax_error("Parameter name 'await' not allowed in this context"); + syntax_error("Parameter name 'await' not allowed in this context"_string); for (auto& previous_name : parameter_names) { if (previous_name == parameter_name) { - syntax_error(ByteString::formatted("Duplicate parameter '{}' not allowed in strict mode", parameter_name)); + syntax_error(MUST(String::formatted("Duplicate parameter '{}' not allowed in strict mode", parameter_name))); } } @@ -2845,14 +2846,14 @@ NonnullRefPtr Parser::parse_function_body(Vector Parser::parse_function_node(u16 parse_options, O } else if (FunctionNodeType::must_have_name() || match_identifier()) { name = create_identifier_and_register_in_current_scope( { m_source_code, rule_start.position(), position() }, - consume_identifier().DeprecatedFlyString_value()); + consume_identifier().fly_string_value()); } else if (is_function_expression && (match(TokenType::Yield) || match(TokenType::Await))) { name = create_identifier_and_register_in_current_scope( { m_source_code, rule_start.position(), position() }, - consume().DeprecatedFlyString_value()); + consume().fly_string_value()); } if (name) { check_identifier_name_for_assignment_validity(name->string()); if (function_kind == FunctionKind::AsyncGenerator && (name->string() == "await"sv || name->string() == "yield"sv)) - syntax_error(ByteString::formatted("async generator function is not allowed to be called '{}'", name->string())); + syntax_error(MUST(String::formatted("async generator function is not allowed to be called '{}'", name->string()))); if (m_state.in_class_static_init_block && name->string() == "await"sv) - syntax_error("'await' is a reserved word"); + syntax_error("'await' is a reserved word"_string); } } TemporaryChange class_static_initializer_rollback(m_state.in_class_static_init_block, false); @@ -3009,7 +3010,7 @@ Vector Parser::parse_formal_parameters(int& function_length, return pattern.release_nonnull(); auto token = consume_identifier(); - auto parameter_name = token.DeprecatedFlyString_value(); + auto parameter_name = token.fly_string_value(); check_identifier_name_for_assignment_validity(parameter_name); @@ -3031,27 +3032,27 @@ Vector Parser::parse_formal_parameters(int& function_length, if (!has_same_name) continue; - ByteString message; + String message; if (parse_options & FunctionNodeParseOptions::IsArrowFunction) - message = ByteString::formatted("Duplicate parameter '{}' not allowed in arrow function", parameter_name); + message = MUST(String::formatted("Duplicate parameter '{}' not allowed in arrow function", parameter_name)); else if (m_state.strict_mode) - message = ByteString::formatted("Duplicate parameter '{}' not allowed in strict mode", parameter_name); + message = MUST(String::formatted("Duplicate parameter '{}' not allowed in strict mode", parameter_name)); else if (has_default_parameter || match(TokenType::Equals)) - message = ByteString::formatted("Duplicate parameter '{}' not allowed in function with default parameter", parameter_name); + message = MUST(String::formatted("Duplicate parameter '{}' not allowed in function with default parameter", parameter_name)); else if (has_rest_parameter) - message = ByteString::formatted("Duplicate parameter '{}' not allowed in function with rest parameter", parameter_name); + message = MUST(String::formatted("Duplicate parameter '{}' not allowed in function with rest parameter", parameter_name)); if (!message.is_empty()) syntax_error(message, Position { token.line_number(), token.line_column() }); break; } - return create_ast_node({ m_source_code, rule_start.position(), position() }, token.DeprecatedFlyString_value()); + return create_ast_node({ m_source_code, rule_start.position(), position() }, token.fly_string_value()); }; while (match(TokenType::CurlyOpen) || match(TokenType::BracketOpen) || match_identifier() || match(TokenType::TripleDot)) { if (parse_options & FunctionNodeParseOptions::IsGetterFunction) - syntax_error("Getter function must have no arguments"); + syntax_error("Getter function must have no arguments"_string); if (parse_options & FunctionNodeParseOptions::IsSetterFunction && (parameters.size() >= 1 || match(TokenType::TripleDot))) - syntax_error("Setter function must have one argument"); + syntax_error("Setter function must have one argument"_string); auto is_rest = false; if (match(TokenType::TripleDot)) { consume(); @@ -3065,7 +3066,7 @@ Vector Parser::parse_formal_parameters(int& function_length, consume(); if (is_rest) - syntax_error("Rest parameter may not have a default initializer"); + syntax_error("Rest parameter may not have a default initializer"_string); TemporaryChange change(m_state.in_function_context, true); has_default_parameter = true; @@ -3074,7 +3075,7 @@ Vector Parser::parse_formal_parameters(int& function_length, bool is_generator = parse_options & FunctionNodeParseOptions::IsGeneratorFunction; if ((is_generator || m_state.strict_mode) && default_value && default_value->fast_is() && static_cast(*default_value).string() == "yield"sv) - syntax_error("Generator function parameter initializer cannot contain a reference to an identifier named \"yield\""); + syntax_error("Generator function parameter initializer cannot contain a reference to an identifier named \"yield\""_string); } parameters.append({ move(parameter), default_value, is_rest }); if (!match(TokenType::Comma) || is_rest) @@ -3082,7 +3083,7 @@ Vector Parser::parse_formal_parameters(int& function_length, consume(TokenType::Comma); } if (parse_options & FunctionNodeParseOptions::IsSetterFunction && parameters.is_empty()) - syntax_error("Setter function must have one argument"); + syntax_error("Setter function must have one argument"_string); // If we're parsing the parameters standalone, e.g. via CreateDynamicFunction, we must have reached EOF here. // Otherwise, we need a closing parenthesis (which is consumed elsewhere). If we get neither, it's an error. if (!match(TokenType::Eof) && !match(TokenType::ParenClose)) @@ -3092,7 +3093,7 @@ Vector Parser::parse_formal_parameters(int& function_length, return parameters; } -static AK::Array s_reserved_words = { "break", "case", "catch", "class", "const", "continue", "debugger", "default", "delete", "do", "else", "enum", "export", "extends", "false", "finally", "for", "function", "if", "import", "in", "instanceof", "new", "null", "return", "super", "switch", "this", "throw", "true", "try", "typeof", "var", "void", "while", "with" }; +static AK::Array s_reserved_words = { "break"_fly_string, "case"_fly_string, "catch"_fly_string, "class"_fly_string, "const"_fly_string, "continue"_fly_string, "debugger"_fly_string, "default"_fly_string, "delete"_fly_string, "do"_fly_string, "else"_fly_string, "enum"_fly_string, "export"_fly_string, "extends"_fly_string, "false"_fly_string, "finally"_fly_string, "for"_fly_string, "function"_fly_string, "if"_fly_string, "import"_fly_string, "in"_fly_string, "instanceof"_fly_string, "new"_fly_string, "null"_fly_string, "return"_fly_string, "super"_fly_string, "switch"_fly_string, "this"_fly_string, "throw"_fly_string, "true"_fly_string, "try"_fly_string, "typeof"_fly_string, "var"_fly_string, "void"_fly_string, "while"_fly_string, "with"_fly_string }; RefPtr Parser::parse_binding_pattern(Parser::AllowDuplicates allow_duplicates, Parser::AllowMemberExpressions allow_member_expressions) { @@ -3142,7 +3143,7 @@ RefPtr Parser::parse_binding_pattern(Parser::AllowDuplicat } else if (is(*expression)) { name = static_ptr_cast(expression); } else { - syntax_error("Invalid destructuring assignment target", expression_position); + syntax_error("Invalid destructuring assignment target"_string, expression_position); return {}; } } else if (match_identifier_name() || match(TokenType::StringLiteral) || match(TokenType::NumericLiteral) || match(TokenType::BigIntLiteral)) { @@ -3154,11 +3155,11 @@ RefPtr Parser::parse_binding_pattern(Parser::AllowDuplicat auto string_literal = parse_string_literal(token); name = create_identifier_and_register_in_current_scope({ m_source_code, rule_start.position(), position() }, string_literal->value()); } else if (match(TokenType::BigIntLiteral)) { - auto string_value = consume().DeprecatedFlyString_value(); - VERIFY(string_value.ends_with("n"sv)); - name = create_identifier_and_register_in_current_scope({ m_source_code, rule_start.position(), position() }, DeprecatedFlyString(string_value.view().substring_view(0, string_value.length() - 1))); + auto string_value = consume().fly_string_value(); + VERIFY(string_value.bytes_as_string_view().ends_with("n"sv)); + name = create_identifier_and_register_in_current_scope({ m_source_code, rule_start.position(), position() }, FlyString(MUST(string_value.to_string().substring_from_byte_offset(0, string_value.bytes().size() - 1)))); } else { - name = create_identifier_and_register_in_current_scope({ m_source_code, rule_start.position(), position() }, consume().DeprecatedFlyString_value()); + name = create_identifier_and_register_in_current_scope({ m_source_code, rule_start.position(), position() }, consume().fly_string_value()); } } else if (match(TokenType::BracketOpen)) { consume(); @@ -3180,7 +3181,7 @@ RefPtr Parser::parse_binding_pattern(Parser::AllowDuplicat if (auto synthesized_binding_pattern = synthesize_binding_pattern(*expression)) { alias = synthesized_binding_pattern.release_nonnull(); } else { - syntax_error("Invalid destructuring assignment target", expression_position); + syntax_error("Invalid destructuring assignment target"_string, expression_position); return {}; } } else if (is(*expression)) { @@ -3188,7 +3189,7 @@ RefPtr Parser::parse_binding_pattern(Parser::AllowDuplicat } else if (is(*expression)) { alias = static_ptr_cast(expression); } else { - syntax_error("Invalid destructuring assignment target", expression_position); + syntax_error("Invalid destructuring assignment target"_string, expression_position); return {}; } } else if (match(TokenType::CurlyOpen) || match(TokenType::BracketOpen)) { @@ -3197,7 +3198,7 @@ RefPtr Parser::parse_binding_pattern(Parser::AllowDuplicat return {}; alias = binding_pattern.release_nonnull(); } else if (match_identifier_name()) { - alias = create_identifier_and_register_in_current_scope({ m_source_code, rule_start.position(), position() }, consume().DeprecatedFlyString_value()); + alias = create_identifier_and_register_in_current_scope({ m_source_code, rule_start.position(), position() }, consume().fly_string_value()); } else { expected("identifier or binding pattern"); return {}; @@ -3215,7 +3216,7 @@ RefPtr Parser::parse_binding_pattern(Parser::AllowDuplicat if (auto synthesized_binding_pattern = synthesize_binding_pattern(*expression)) { alias = synthesized_binding_pattern.release_nonnull(); } else { - syntax_error("Invalid destructuring assignment target", expression_position); + syntax_error("Invalid destructuring assignment target"_string, expression_position); return {}; } } else if (is(*expression)) { @@ -3223,7 +3224,7 @@ RefPtr Parser::parse_binding_pattern(Parser::AllowDuplicat } else if (is(*expression)) { alias = static_ptr_cast(expression); } else { - syntax_error("Invalid destructuring assignment target", expression_position); + syntax_error("Invalid destructuring assignment target"_string, expression_position); return {}; } } else if (match(TokenType::BracketOpen) || match(TokenType::CurlyOpen)) { @@ -3235,7 +3236,7 @@ RefPtr Parser::parse_binding_pattern(Parser::AllowDuplicat alias = pattern.release_nonnull(); } else if (match_identifier_name()) { // BindingElement must always have an Empty name field - auto identifier_name = consume_identifier().DeprecatedFlyString_value(); + auto identifier_name = consume_identifier().fly_string_value(); alias = create_identifier_and_register_in_current_scope({ m_source_code, rule_start.position(), position() }, identifier_name); } else { expected("identifier or binding pattern"); @@ -3245,7 +3246,7 @@ RefPtr Parser::parse_binding_pattern(Parser::AllowDuplicat if (match(TokenType::Equals)) { if (is_rest) { - syntax_error("Unexpected initializer after rest element"); + syntax_error("Unexpected initializer after rest element"_string); return {}; } @@ -3262,7 +3263,7 @@ RefPtr Parser::parse_binding_pattern(Parser::AllowDuplicat if (match(TokenType::Comma)) { if (is_rest) { - syntax_error("Rest element may not be followed by a comma"); + syntax_error("Rest element may not be followed by a comma"_string); return {}; } consume(); @@ -3287,7 +3288,7 @@ RefPtr Parser::parse_binding_pattern(Parser::AllowDuplicat auto const& name = identifier.string(); if (allow_duplicates == AllowDuplicates::No) { if (bound_names.contains_slow(name)) - syntax_error("Duplicate parameter names in bindings"); + syntax_error("Duplicate parameter names in bindings"_string); bound_names.append(name); } check_identifier_name_for_assignment_validity(name); @@ -3301,19 +3302,19 @@ RefPtr Parser::parse_lexical_binding(Optional auto binding_start = push_start(); if (match_identifier()) { - return create_identifier_and_register_in_current_scope({ m_source_code, binding_start.position(), position() }, consume_identifier().DeprecatedFlyString_value(), declaration_kind); + return create_identifier_and_register_in_current_scope({ m_source_code, binding_start.position(), position() }, consume_identifier().fly_string_value(), declaration_kind); } if (!m_state.in_generator_function_context && match(TokenType::Yield)) { if (m_state.strict_mode) - syntax_error("Identifier must not be a reserved word in strict mode ('yield')"); + syntax_error("Identifier must not be a reserved word in strict mode ('yield')"_string); - return create_identifier_and_register_in_current_scope({ m_source_code, binding_start.position(), position() }, consume().DeprecatedFlyString_value(), declaration_kind); + return create_identifier_and_register_in_current_scope({ m_source_code, binding_start.position(), position() }, consume().fly_string_value(), declaration_kind); } if (!m_state.await_expression_is_valid && match(TokenType::Async)) { if (m_program_type == Program::Type::Module) - syntax_error("Identifier must not be a reserved word in modules ('async')"); + syntax_error("Identifier must not be a reserved word in modules ('async')"_string); - return create_identifier_and_register_in_current_scope({ m_source_code, binding_start.position(), position() }, consume().DeprecatedFlyString_value(), declaration_kind); + return create_identifier_and_register_in_current_scope({ m_source_code, binding_start.position(), position() }, consume().fly_string_value(), declaration_kind); } return {}; @@ -3347,7 +3348,7 @@ NonnullRefPtr Parser::parse_variable_declaration(IsFo // NOTE: Nothing in the callback throws an exception. MUST(pattern->for_each_bound_identifier([this](auto& identifier) { if (identifier.string() == "let"sv) - syntax_error("Lexical binding may not be called 'let'"); + syntax_error("Lexical binding may not be called 'let'"_string); })); } @@ -3355,7 +3356,7 @@ NonnullRefPtr Parser::parse_variable_declaration(IsFo } else if (auto lexical_binding = parse_lexical_binding(declaration_kind)) { check_identifier_name_for_assignment_validity(lexical_binding->string()); if ((declaration_kind == DeclarationKind::Let || declaration_kind == DeclarationKind::Const) && lexical_binding->string() == "let"sv) - syntax_error("Lexical binding may not be called 'let'"); + syntax_error("Lexical binding may not be called 'let'"_string); target = lexical_binding.release_nonnull(); } @@ -3379,9 +3380,9 @@ NonnullRefPtr Parser::parse_variable_declaration(IsFo else init = parse_expression(2); } else if (is_for_loop_variable_declaration == IsForLoopVariableDeclaration::No && declaration_kind == DeclarationKind::Const) { - syntax_error("Missing initializer in 'const' variable declaration"); + syntax_error("Missing initializer in 'const' variable declaration"_string); } else if (is_for_loop_variable_declaration == IsForLoopVariableDeclaration::No && target.has>()) { - syntax_error("Missing initializer in destructuring assignment"); + syntax_error("Missing initializer in destructuring assignment"_string); } declarations.append(create_ast_node( @@ -3422,7 +3423,7 @@ NonnullRefPtr Parser::parse_using_declaration(IsForLoopV check_identifier_name_for_assignment_validity(lexical_binding->string()); if (lexical_binding->string() == "let"sv) - syntax_error("Lexical binding may not be called 'let'"); + syntax_error("Lexical binding may not be called 'let'"_string); RefPtr initializer; if (match(TokenType::Equals)) { @@ -3460,7 +3461,7 @@ NonnullRefPtr Parser::parse_throw_statement() // Automatic semicolon insertion: terminate statement when throw is followed by newline if (m_state.current_token.trivia_contains_line_terminator()) { - syntax_error("No line break is allowed between 'throw' and its expression"); + syntax_error("No line break is allowed between 'throw' and its expression"_string); return create_ast_node({ m_source_code, rule_start.position(), position() }, create_ast_node({ m_source_code, rule_start.position(), position() })); } @@ -3473,22 +3474,22 @@ NonnullRefPtr Parser::parse_break_statement() { auto rule_start = push_start(); consume(TokenType::Break); - Optional target_label; + Optional target_label; if (match(TokenType::Semicolon)) { consume(); } else { if (!m_state.current_token.trivia_contains_line_terminator() && match_identifier()) { - target_label = consume().value(); + target_label = consume().fly_string_value(); auto label = m_state.labels_in_scope.find(target_label.value()); if (label == m_state.labels_in_scope.end()) - syntax_error(ByteString::formatted("Label '{}' not found", target_label.value())); + syntax_error(MUST(String::formatted("Label '{}' not found", target_label.value()))); } consume_or_insert_semicolon(); } if (!target_label.has_value() && !m_state.in_break_context) - syntax_error("Unlabeled 'break' not allowed outside of a loop or switch statement"); + syntax_error("Unlabeled 'break' not allowed outside of a loop or switch statement"_string); return create_ast_node({ m_source_code, rule_start.position(), position() }, target_label); } @@ -3497,21 +3498,21 @@ NonnullRefPtr Parser::parse_continue_statement() { auto rule_start = push_start(); if (!m_state.in_continue_context) - syntax_error("'continue' not allow outside of a loop"); + syntax_error("'continue' not allow outside of a loop"_string); consume(TokenType::Continue); - Optional target_label; + Optional target_label; if (match(TokenType::Semicolon)) { consume(); return create_ast_node({ m_source_code, rule_start.position(), position() }, target_label); } if (!m_state.current_token.trivia_contains_line_terminator() && match_identifier()) { auto label_position = position(); - target_label = consume().value(); + target_label = consume().fly_string_value(); auto label = m_state.labels_in_scope.find(target_label.value()); if (label == m_state.labels_in_scope.end()) - syntax_error(ByteString::formatted("Label '{}' not found or invalid", target_label.value())); + syntax_error(MUST(String::formatted("Label '{}' not found or invalid", target_label.value()))); else label->value = label_position; } @@ -3547,12 +3548,12 @@ NonnullRefPtr Parser::parse_optional_chain(NonnullRefPtr({ m_source_code, start, position() }, private_identifier.value()), + create_ast_node({ m_source_code, start, position() }, private_identifier.fly_string_value()), OptionalChain::Mode::Optional }); break; } @@ -3562,18 +3563,18 @@ NonnullRefPtr Parser::parse_optional_chain(NonnullRefPtr({ m_source_code, start, position() }, identifier.DeprecatedFlyString_value()), + create_ast_node({ m_source_code, start, position() }, identifier.fly_string_value()), OptionalChain::Mode::Optional, }); } else { - syntax_error("Invalid optional chain reference after ?.", position()); + syntax_error("Invalid optional chain reference after ?."_string, position()); } break; } @@ -3583,19 +3584,19 @@ NonnullRefPtr Parser::parse_optional_chain(NonnullRefPtr({ m_source_code, start, position() }, private_identifier.value()), + create_ast_node({ m_source_code, start, position() }, private_identifier.fly_string_value()), OptionalChain::Mode::NotOptional, }); } else if (match_identifier_name()) { auto start = position(); auto identifier = consume_and_allow_division(); chain.append(OptionalChain::MemberReference { - create_ast_node({ m_source_code, start, position() }, identifier.DeprecatedFlyString_value()), + create_ast_node({ m_source_code, start, position() }, identifier.fly_string_value()), OptionalChain::Mode::NotOptional, }); } else { @@ -3607,7 +3608,7 @@ NonnullRefPtr Parser::parse_optional_chain(NonnullRefPtr Parser::parse_try_statement() } if (!handler && !finalizer) - syntax_error("try statement must have a 'catch' or 'finally' clause"); + syntax_error("try statement must have a 'catch' or 'finally' clause"_string); return create_ast_node({ m_source_code, rule_start.position(), position() }, move(block), move(handler), move(finalizer)); } @@ -3710,7 +3711,7 @@ NonnullRefPtr Parser::parse_switch_statement() while (match(TokenType::Case) || match(TokenType::Default)) { if (match(TokenType::Default)) { if (has_default) - syntax_error("Multiple 'default' clauses in switch statement"); + syntax_error("Multiple 'default' clauses in switch statement"_string); has_default = true; } switch_statement->add_case(parse_switch_case()); @@ -3762,7 +3763,7 @@ NonnullRefPtr Parser::parse_catch_clause() auto rule_start = push_start(); consume(TokenType::Catch); - DeprecatedFlyString parameter; + FlyString parameter; RefPtr pattern_parameter; auto should_expect_parameter = false; if (match(TokenType::ParenOpen)) { @@ -3773,7 +3774,7 @@ NonnullRefPtr Parser::parse_catch_clause() && (!match(TokenType::Yield) || !m_state.in_generator_function_context) && (!match(TokenType::Async) || !m_state.await_expression_is_valid) && (!match(TokenType::Await) || !m_state.in_class_static_init_block)) - parameter = consume().value(); + parameter = consume().fly_string_value(); else pattern_parameter = parse_binding_pattern(AllowDuplicates::No, AllowMemberExpressions::No); consume(TokenType::ParenClose); @@ -3782,7 +3783,7 @@ NonnullRefPtr Parser::parse_catch_clause() if (should_expect_parameter && parameter.is_empty() && !pattern_parameter) expected("an identifier or a binding pattern"); - HashTable bound_names; + HashTable bound_names; if (pattern_parameter) { // NOTE: Nothing in the callback throws an exception. @@ -3804,7 +3805,7 @@ NonnullRefPtr Parser::parse_catch_clause() // NOTE: Nothing in the callback throws an exception. MUST(body->for_each_lexically_declared_identifier([&](auto const& identifier) { if (bound_names.contains(identifier.string())) - syntax_error(ByteString::formatted("Identifier '{}' already declared as catch parameter", identifier.string())); + syntax_error(MUST(String::formatted("Identifier '{}' already declared as catch parameter", identifier.string()))); })); if (pattern_parameter) { @@ -3841,9 +3842,9 @@ NonnullRefPtr Parser::parse_if_statement() VERIFY(is(*declaration)); auto& function_declaration = static_cast(*declaration); if (function_declaration.kind() == FunctionKind::Generator) - syntax_error("Generator functions can only be declared in top-level or within a block"); + syntax_error("Generator functions can only be declared in top-level or within a block"_string); if (function_declaration.kind() == FunctionKind::Async) - syntax_error("Async functions can only be declared in top-level or within a block"); + syntax_error("Async functions can only be declared in top-level or within a block"_string); block->append(move(declaration)); return block; }; @@ -3886,9 +3887,9 @@ NonnullRefPtr Parser::parse_for_statement() bool is_of = match_of(m_state.current_token); if (is_await_loop == IsForAwaitLoop::Yes) { if (!is_of) - syntax_error("for await loop is only valid with 'of'"); + syntax_error("for await loop is only valid with 'of'"_string); else if (!m_state.await_expression_is_valid) - syntax_error("for await loop is only valid in async function or generator"); + syntax_error("for await loop is only valid in async function or generator"_string); return true; } @@ -3900,7 +3901,7 @@ NonnullRefPtr Parser::parse_for_statement() if (match(TokenType::Await)) { consume(); if (!m_state.await_expression_is_valid) - syntax_error("for-await-of is only allowed in async function context"); + syntax_error("for-await-of is only allowed in async function context"_string); is_await_loop = IsForAwaitLoop::Yes; } @@ -3930,15 +3931,15 @@ NonnullRefPtr Parser::parse_for_statement() if (match_of(m_state.current_token)) { if (declaration->declarations().size() != 1) - syntax_error("Must have exactly one declaration in for using of"); + syntax_error("Must have exactly one declaration in for using of"_string); else if (declaration->declarations().first()->init()) - syntax_error("Using declaration cannot have initializer"); + syntax_error("Using declaration cannot have initializer"_string); return parse_for_in_of_statement(move(declaration), is_await_loop); } if (match(TokenType::In)) - syntax_error("Using declaration not allowed in for-in loop"); + syntax_error("Using declaration not allowed in for-in loop"_string); init = move(declaration); } else if (match_variable_declaration()) { @@ -3946,16 +3947,16 @@ NonnullRefPtr Parser::parse_for_statement() m_state.current_scope_pusher->add_declaration(declaration); if (match_for_in_of()) { if (declaration->declarations().size() > 1) - syntax_error("Multiple declarations not allowed in for..in/of"); + syntax_error("Multiple declarations not allowed in for..in/of"_string); else if (declaration->declarations().size() < 1) - syntax_error("Need exactly one variable declaration in for..in/of"); + syntax_error("Need exactly one variable declaration in for..in/of"_string); return parse_for_in_of_statement(move(declaration), is_await_loop); } if (declaration->declaration_kind() == DeclarationKind::Const) { for (auto const& variable : declaration->declarations()) { if (!variable->init()) - syntax_error("Missing initializer in 'const' variable declaration"); + syntax_error("Missing initializer in 'const' variable declaration"_string); } } @@ -3968,11 +3969,11 @@ NonnullRefPtr Parser::parse_for_statement() if (match_for_in_of()) { if (is_await_loop != IsForAwaitLoop::Yes && starts_with_async_of && match_of(m_state.current_token)) - syntax_error("for-of loop may not start with async of"); + syntax_error("for-of loop may not start with async of"_string); return parse_for_in_of_statement(*init, is_await_loop); } } else { - syntax_error("Unexpected token in for loop"); + syntax_error("Unexpected token in for loop"_string); } } consume(TokenType::Semicolon); @@ -4012,7 +4013,7 @@ NonnullRefPtr Parser::parse_for_in_of_statement(NonnullRefPtrinit()) { if (m_state.strict_mode || declaration.declaration_kind() != DeclarationKind::Var || !variable->target().has>()) - syntax_error("Variable initializer not allowed in for..in/of"); + syntax_error("Variable initializer not allowed in for..in/of"_string); else has_annexB_for_in_init_extension = true; } @@ -4027,7 +4028,7 @@ NonnullRefPtr Parser::parse_for_in_of_statement(NonnullRefPtrclass_name())); + syntax_error(MUST(String::formatted("Invalid left-hand side in for-loop ('{}')", lhs->class_name()))); } auto in_or_of = consume(); auto is_in = in_or_of.type() == TokenType::In; @@ -4036,10 +4037,10 @@ NonnullRefPtr Parser::parse_for_in_of_statement(NonnullRefPtr(*lhs)) { auto& member = static_cast(*lhs); if (member.object().is_identifier() && static_cast(member.object()).string() == "let"sv) - syntax_error("For of statement may not start with let."); + syntax_error("For of statement may not start with let."_string); } if (has_annexB_for_in_init_extension) - syntax_error("Variable initializer not allowed in for..of", rule_start.position()); + syntax_error("Variable initializer not allowed in for..of"_string, rule_start.position()); } auto rhs = parse_expression(is_in ? 0 : 2); @@ -4385,19 +4386,19 @@ Token Parser::consume_identifier() // special-case it here instead. if (match(TokenType::Let)) { if (m_state.strict_mode) - syntax_error("'let' is not allowed as an identifier in strict mode"); + syntax_error("'let' is not allowed as an identifier in strict mode"_string); return consume_and_allow_division(); } if (match(TokenType::Yield)) { if (m_state.strict_mode || m_state.in_generator_function_context) - syntax_error("Identifier must not be a reserved word in strict mode ('yield')"); + syntax_error("Identifier must not be a reserved word in strict mode ('yield')"_string); return consume_and_allow_division(); } if (match(TokenType::Await)) { if (m_program_type == Program::Type::Module || m_state.await_expression_is_valid || m_state.in_class_static_init_block) - syntax_error("Identifier must not be a reserved word in modules ('await')"); + syntax_error("Identifier must not be a reserved word in modules ('await')"_string); return consume_and_allow_division(); } @@ -4417,9 +4418,9 @@ Token Parser::consume_identifier_reference() if (match(TokenType::EscapedKeyword)) { auto name = m_state.current_token.value(); if (m_state.strict_mode && (name == "let"sv || name == "yield"sv)) - syntax_error(ByteString::formatted("'{}' is not allowed as an identifier in strict mode", name)); + syntax_error(MUST(String::formatted("'{}' is not allowed as an identifier in strict mode", name))); if (m_program_type == Program::Type::Module && name == "await"sv) - syntax_error("'await' is not allowed as an identifier in module"); + syntax_error("'await' is not allowed as an identifier in module"_string); return consume_and_allow_division(); } @@ -4427,19 +4428,19 @@ Token Parser::consume_identifier_reference() // See note in Parser::parse_identifier(). if (match(TokenType::Let)) { if (m_state.strict_mode) - syntax_error("'let' is not allowed as an identifier in strict mode"); + syntax_error("'let' is not allowed as an identifier in strict mode"_string); return consume_and_allow_division(); } if (match(TokenType::Yield)) { if (m_state.strict_mode) - syntax_error("Identifier reference may not be 'yield' in strict mode"); + syntax_error("Identifier reference may not be 'yield' in strict mode"_string); return consume_and_allow_division(); } if (match(TokenType::Await)) { if (m_program_type == Program::Type::Module) - syntax_error("'await' is not allowed as an identifier in module"); + syntax_error("'await' is not allowed as an identifier in module"_string); return consume_and_allow_division(); } @@ -4458,7 +4459,7 @@ Token Parser::consume(TokenType expected_type) auto token = expected_type == TokenType::Identifier ? consume_and_allow_division() : consume(); if (expected_type == TokenType::Identifier) { if (m_state.strict_mode && is_strict_reserved_word(token.value())) - syntax_error(ByteString::formatted("Identifier must not be a reserved word in strict mode ('{}')", token.value())); + syntax_error(MUST(String::formatted("Identifier must not be a reserved word in strict mode ('{}')", token.value()))); } return token; } @@ -4471,17 +4472,17 @@ Token Parser::consume_and_validate_numeric_literal() auto literal_start = position(); auto token = consume(TokenType::NumericLiteral); if (m_state.strict_mode && is_unprefixed_octal_number(token.value())) - syntax_error("Unprefixed octal number not allowed in strict mode", literal_start); + syntax_error("Unprefixed octal number not allowed in strict mode"_string, literal_start); if (match_identifier_name() && m_state.current_token.trivia().is_empty()) - syntax_error("Numeric literal must not be immediately followed by identifier"); + syntax_error("Numeric literal must not be immediately followed by identifier"_string); return token; } void Parser::expected(char const* what) { - auto message = m_state.current_token.message().to_byte_string(); + auto message = MUST(String::from_utf8(m_state.current_token.message())); if (message.is_empty()) - message = ByteString::formatted("Unexpected token {}. Expected {}", m_state.current_token.name(), what); + message = MUST(String::formatted("Unexpected token {}. Expected {}", m_state.current_token.name(), what)); syntax_error(message); } @@ -4508,7 +4509,7 @@ void Parser::set_try_parse_arrow_function_expression_failed_at_position(Position m_token_memoizations.set(position.offset, { failed }); } -void Parser::syntax_error(ByteString const& message, Optional position) +void Parser::syntax_error(String const& message, Optional position) { if (!position.has_value()) position = this->position(); @@ -4531,35 +4532,35 @@ void Parser::discard_saved_state() m_saved_state.take_last(); } -void Parser::check_identifier_name_for_assignment_validity(DeprecatedFlyString const& name, bool force_strict) +void Parser::check_identifier_name_for_assignment_validity(FlyString const& name, bool force_strict) { // FIXME: this is now called from multiple places maybe the error message should be dynamic? if (any_of(s_reserved_words, [&](auto& value) { return name == value; })) { - syntax_error("Binding pattern target may not be a reserved word"); + syntax_error("Binding pattern target may not be a reserved word"_string); } else if (m_state.strict_mode || force_strict) { if (name.is_one_of("arguments"sv, "eval"sv)) - syntax_error("Binding pattern target may not be called 'arguments' or 'eval' in strict mode"); + syntax_error("Binding pattern target may not be called 'arguments' or 'eval' in strict mode"_string); else if (is_strict_reserved_word(name)) - syntax_error(ByteString::formatted("Binding pattern target may not be called '{}' in strict mode", name)); + syntax_error(MUST(String::formatted("Binding pattern target may not be called '{}' in strict mode", name))); } } -DeprecatedFlyString Parser::consume_string_value() +FlyString Parser::consume_string_value() { VERIFY(match(TokenType::StringLiteral)); auto string_token = consume(); - DeprecatedFlyString value = parse_string_literal(string_token)->value(); + FlyString value = parse_string_literal(string_token)->value(); // This also checks IsStringWellFormedUnicode which makes sure there is no unpaired surrogate // Surrogates are at least 3 bytes - if (value.length() < 3) + if (value.bytes().size() < 3) return value; - Utf8View view { value.view().substring_view(value.length() - 3) }; + Utf8View view { value.bytes_as_string_view().substring_view(value.bytes().size() - 3) }; VERIFY(view.length() <= 3); auto codepoint = *view.begin(); if (Utf16View::is_high_surrogate(codepoint)) { - syntax_error("StringValue ending with unpaired high surrogate"); + syntax_error("StringValue ending with unpaired high surrogate"_string); VERIFY(view.length() == 1); } @@ -4573,7 +4574,7 @@ ModuleRequest Parser::parse_module_request() if (!match(TokenType::StringLiteral)) { expected("ModuleSpecifier (string)"); - return ModuleRequest { "!!invalid!!" }; + return ModuleRequest { "!!invalid!!"_fly_string }; } ModuleRequest request { consume_string_value() }; @@ -4585,12 +4586,12 @@ ModuleRequest Parser::parse_module_request() consume(TokenType::CurlyOpen); while (!done() && !match(TokenType::CurlyClose)) { - ByteString key; + String key; if (match(TokenType::StringLiteral)) { key = parse_string_literal(m_state.current_token)->value(); consume(); } else if (match_identifier_name()) { - key = consume().value(); + key = consume().fly_string_value().to_string(); } else { expected("IdentifierName or StringValue as WithKey"); consume(); @@ -4601,7 +4602,7 @@ ModuleRequest Parser::parse_module_request() if (match(TokenType::StringLiteral)) { for (auto& entries : request.attributes) { if (entries.key == key) - syntax_error(ByteString::formatted("Duplicate attribute clauses with name: {}", key)); + syntax_error(MUST(String::formatted("Duplicate attribute clauses with name: {}", key))); } request.add_attribute(move(key), parse_string_literal(m_state.current_token)->value()); } @@ -4618,7 +4619,7 @@ ModuleRequest Parser::parse_module_request() return request; } -static DeprecatedFlyString default_string_value = "default"; +static FlyString default_string_value = "default"_fly_string; NonnullRefPtr Parser::parse_import_statement(Program& program) { @@ -4630,7 +4631,7 @@ NonnullRefPtr Parser::parse_import_statement(Program& pro auto rule_start = push_start(); if (program.type() != Program::Type::Module) - syntax_error("Cannot use import statement outside a module"); + syntax_error("Cannot use import statement outside a module"_string); consume(TokenType::Import); @@ -4668,7 +4669,7 @@ NonnullRefPtr Parser::parse_import_statement(Program& pro if (match_imported_binding()) { // ImportedDefaultBinding : ImportedBinding auto id_position = position(); - auto bound_name = consume().value(); + auto bound_name = consume().fly_string_value(); entries_with_location.append({ { default_string_value, bound_name }, id_position }); if (match(TokenType::Comma)) { @@ -4685,16 +4686,16 @@ NonnullRefPtr Parser::parse_import_statement(Program& pro consume(TokenType::Asterisk); if (!match_as()) - syntax_error(ByteString::formatted("Unexpected token: {}", m_state.current_token.name())); + syntax_error(MUST(String::formatted("Unexpected token: {}", m_state.current_token.name()))); consume(TokenType::Identifier); if (match_imported_binding()) { auto namespace_position = position(); - auto namespace_name = consume().value(); + auto namespace_name = consume().fly_string_value(); entries_with_location.append({ ImportEntry({}, namespace_name), namespace_position }); } else { - syntax_error(ByteString::formatted("Unexpected token: {}", m_state.current_token.name())); + syntax_error(MUST(String::formatted("Unexpected token: {}", m_state.current_token.name()))); } } else if (match(TokenType::CurlyOpen)) { @@ -4707,18 +4708,18 @@ NonnullRefPtr Parser::parse_import_statement(Program& pro // ImportSpecifier : ImportedBinding auto require_as = !match_imported_binding(); auto name_position = position(); - auto name = consume().DeprecatedFlyString_value(); + auto name = consume().fly_string_value(); if (match_as()) { consume(TokenType::Identifier); auto alias_position = position(); - auto alias = consume_identifier().DeprecatedFlyString_value(); + auto alias = consume_identifier().fly_string_value(); check_identifier_name_for_assignment_validity(alias); entries_with_location.append({ { name, alias }, alias_position }); } else if (require_as) { - syntax_error(ByteString::formatted("Unexpected reserved word '{}'", name)); + syntax_error(MUST(String::formatted("Unexpected reserved word '{}'", name))); } else { check_identifier_name_for_assignment_validity(name); @@ -4734,7 +4735,7 @@ NonnullRefPtr Parser::parse_import_statement(Program& pro consume(TokenType::Identifier); auto alias_position = position(); - auto alias = consume_identifier().DeprecatedFlyString_value(); + auto alias = consume_identifier().fly_string_value(); check_identifier_name_for_assignment_validity(alias); entries_with_location.append({ { move(name), alias }, alias_position }); @@ -4756,7 +4757,7 @@ NonnullRefPtr Parser::parse_import_statement(Program& pro auto from_statement = consume(TokenType::Identifier).original_value(); if (from_statement != "from"sv) - syntax_error(ByteString::formatted("Expected 'from' got {}", from_statement)); + syntax_error(MUST(String::formatted("Expected 'from' got {}", from_statement))); auto module_request = parse_module_request(); @@ -4766,12 +4767,12 @@ NonnullRefPtr Parser::parse_import_statement(Program& pro for (auto& entry : entries_with_location) { for (auto& import_statement : program.imports()) { if (import_statement->has_bound_name(entry.entry.local_name)) - syntax_error(ByteString::formatted("Identifier '{}' already declared", entry.entry.local_name), entry.position); + syntax_error(MUST(String::formatted("Identifier '{}' already declared", entry.entry.local_name)), entry.position); } for (auto& new_entry : entries) { if (new_entry.local_name == entry.entry.local_name) - syntax_error(ByteString::formatted("Identifier '{}' already declared", entry.entry.local_name), entry.position); + syntax_error(MUST(String::formatted("Identifier '{}' already declared", entry.entry.local_name)), entry.position); } entries.append(move(entry.entry)); @@ -4789,7 +4790,7 @@ NonnullRefPtr Parser::parse_export_statement(Program& pro auto rule_start = push_start(); if (program.type() != Program::Type::Module) - syntax_error("Cannot use export statement outside a module"); + syntax_error("Cannot use export statement outside a module"_string); auto match_as = [&] { return match(TokenType::Identifier) && m_state.current_token.original_value() == "as"sv; @@ -4821,7 +4822,7 @@ NonnullRefPtr Parser::parse_export_statement(Program& pro auto default_position = position(); consume(TokenType::Default); - Optional local_name; + Optional local_name; auto lookahead_token = next_token(); @@ -4921,7 +4922,7 @@ NonnullRefPtr Parser::parse_export_statement(Program& pro } } else { expected("Declaration or assignment expression"); - local_name = "!!invalid!!"; + local_name = "!!invalid!!"_fly_string; } if (!local_name.has_value()) @@ -4935,13 +4936,13 @@ NonnullRefPtr Parser::parse_export_statement(Program& pro Required } check_for_from { FromSpecifier::NotAllowed }; - auto parse_module_export_name = [&](bool lhs) -> DeprecatedFlyString { + auto parse_module_export_name = [&](bool lhs) -> FlyString { // https://tc39.es/ecma262/#prod-ModuleExportName // ModuleExportName : // IdentifierName // StringLiteral if (match_identifier_name()) { - return consume().value(); + return consume().fly_string_value(); } if (match(TokenType::StringLiteral)) { // It is a Syntax Error if ReferencedBindings of NamedExports contains any StringLiterals. @@ -5049,7 +5050,7 @@ NonnullRefPtr Parser::parse_export_statement(Program& pro consume(TokenType::CurlyClose); } else { - syntax_error("Unexpected token 'export'", rule_start.position()); + syntax_error("Unexpected token 'export'"_string, rule_start.position()); } if (check_for_from != FromSpecifier::NotAllowed && match_from()) { @@ -5068,13 +5069,13 @@ NonnullRefPtr Parser::parse_export_statement(Program& pro for (auto& entry : entries_with_location) { for (auto& export_statement : program.exports()) { - if (export_statement->has_export(entry.entry.export_name.value_or(""))) - syntax_error(ByteString::formatted("Duplicate export with name: '{}'", entry.entry.export_name), entry.position); + if (export_statement->has_export(entry.entry.export_name.value_or(""_fly_string))) + syntax_error(MUST(String::formatted("Duplicate export with name: '{}'", entry.entry.export_name)), entry.position); } for (auto& new_entry : entries) { if (new_entry.kind != ExportEntry::Kind::EmptyNamedExport && new_entry.export_name == entry.entry.export_name) - syntax_error(ByteString::formatted("Duplicate export with name: '{}'", entry.entry.export_name), entry.position); + syntax_error(MUST(String::formatted("Duplicate export with name: '{}'", entry.entry.export_name)), entry.position); } entries.append(move(entry.entry)); @@ -5160,7 +5161,7 @@ Parser::ForbiddenTokens Parser::ForbiddenTokens::forbid(std::initializer_list Parser::parse_function_node(u16, Optional const&); template NonnullRefPtr Parser::parse_function_node(u16, Optional const&); -NonnullRefPtr Parser::create_identifier_and_register_in_current_scope(SourceRange range, DeprecatedFlyString string, Optional declaration_kind) +NonnullRefPtr Parser::create_identifier_and_register_in_current_scope(SourceRange range, FlyString string, Optional declaration_kind) { auto id = create_ast_node(range, string); if (m_state.current_scope_pusher) diff --git a/Libraries/LibJS/Parser.h b/Libraries/LibJS/Parser.h index 4a5bb2facba..7129fa8fd5c 100644 --- a/Libraries/LibJS/Parser.h +++ b/Libraries/LibJS/Parser.h @@ -243,7 +243,7 @@ private: bool match(TokenType type) const; bool done() const; void expected(char const* what); - void syntax_error(ByteString const& message, Optional = {}); + void syntax_error(String const& message, Optional = {}); Token consume(); Token consume_and_allow_division(); Token consume_identifier(); @@ -260,7 +260,7 @@ private: Token next_token(size_t steps = 1) const; - void check_identifier_name_for_assignment_validity(DeprecatedFlyString const&, bool force_strict = false); + void check_identifier_name_for_assignment_validity(FlyString const&, bool force_strict = false); bool try_parse_arrow_function_expression_failed_at_position(Position const&) const; void set_try_parse_arrow_function_expression_failed_at_position(Position const&, bool); @@ -270,7 +270,7 @@ private: bool parse_directive(ScopeNode& body); void parse_statement_list(ScopeNode& output_node, AllowLabelledFunction allow_labelled_functions = AllowLabelledFunction::No); - DeprecatedFlyString consume_string_value(); + FlyString consume_string_value(); ModuleRequest parse_module_request(); struct RulePosition { @@ -308,9 +308,9 @@ private: Vector errors; ScopePusher* current_scope_pusher { nullptr }; - HashMap> labels_in_scope; + HashMap> labels_in_scope; HashMap invalid_property_range_in_object_expression; - HashTable* referenced_private_names { nullptr }; + HashTable* referenced_private_names { nullptr }; bool strict_mode { false }; bool allow_super_property_lookup { false }; @@ -333,7 +333,7 @@ private: ParserState(Lexer, Program::Type); }; - [[nodiscard]] NonnullRefPtr create_identifier_and_register_in_current_scope(SourceRange range, DeprecatedFlyString string, Optional = {}); + [[nodiscard]] NonnullRefPtr create_identifier_and_register_in_current_scope(SourceRange range, FlyString string, Optional = {}); NonnullRefPtr m_source_code; Vector m_rule_starts; diff --git a/Libraries/LibJS/ParserError.cpp b/Libraries/LibJS/ParserError.cpp index b47ab1584df..26c12a4ee80 100644 --- a/Libraries/LibJS/ParserError.cpp +++ b/Libraries/LibJS/ParserError.cpp @@ -15,14 +15,14 @@ namespace JS { String ParserError::to_string() const { if (!position.has_value()) - return MUST(String::from_byte_string(message)); + return message; return MUST(String::formatted("{} (line: {}, column: {})", message, position.value().line, position.value().column)); } ByteString ParserError::to_byte_string() const { if (!position.has_value()) - return message; + return message.to_byte_string(); return ByteString::formatted("{} (line: {}, column: {})", message, position.value().line, position.value().column); } diff --git a/Libraries/LibJS/ParserError.h b/Libraries/LibJS/ParserError.h index 143b1121d26..eb48518aa60 100644 --- a/Libraries/LibJS/ParserError.h +++ b/Libraries/LibJS/ParserError.h @@ -16,7 +16,7 @@ namespace JS { struct ParserError { - ByteString message; + String message; Optional position; String to_string() const; diff --git a/Libraries/LibJS/Runtime/AbstractOperations.cpp b/Libraries/LibJS/Runtime/AbstractOperations.cpp index 1089d36f123..e089063eb10 100644 --- a/Libraries/LibJS/Runtime/AbstractOperations.cpp +++ b/Libraries/LibJS/Runtime/AbstractOperations.cpp @@ -206,7 +206,7 @@ ThrowCompletionOr get_function_realm(VM& vm, FunctionObject const& funct } // 8.5.2.1 InitializeBoundName ( name, value, environment ), https://tc39.es/ecma262/#sec-initializeboundname -ThrowCompletionOr initialize_bound_name(VM& vm, DeprecatedFlyString const& name, Value value, Environment* environment) +ThrowCompletionOr initialize_bound_name(VM& vm, FlyString const& name, Value value, Environment* environment) { // 1. If environment is not undefined, then if (environment) { @@ -692,7 +692,7 @@ ThrowCompletionOr perform_eval(VM& vm, Value x, CallerMode strict_caller, return vm.throw_completion(ErrorType::NotImplemented, TRY_OR_THROW_OOM(vm, executable_result.error().to_string())); auto executable = executable_result.release_value(); - executable->name = "eval"sv; + executable->name = "eval"_fly_string; if (Bytecode::g_dump_bytecode) executable->dump(); auto result_or_error = vm.bytecode_interpreter().run_executable(*executable, {}); @@ -779,7 +779,7 @@ ThrowCompletionOr eval_declaration_instantiation(VM& vm, Program const& pr Vector functions_to_initialize; // 9. Let declaredFunctionNames be a new empty List. - HashTable declared_function_names; + HashTable declared_function_names; // 10. For each element d of varDeclarations, in reverse List order, do TRY(program.for_each_var_function_declaration_in_reverse_order([&](FunctionDeclaration const& function) -> ThrowCompletionOr { @@ -820,7 +820,7 @@ ThrowCompletionOr eval_declaration_instantiation(VM& vm, Program const& pr if (!strict) { // a. Let declaredFunctionOrVarNames be the list-concatenation of declaredFunctionNames and declaredVarNames. // The spec here uses 'declaredVarNames' but that has not been declared yet. - HashTable hoisted_functions; + HashTable hoisted_functions; // b. For each FunctionDeclaration f that is directly contained in the StatementList of a Block, CaseClause, or DefaultClause Contained within body, do TRY(program.for_each_function_hoistable_with_annexB_extension([&](FunctionDeclaration& function_declaration) -> ThrowCompletionOr { @@ -911,7 +911,7 @@ ThrowCompletionOr eval_declaration_instantiation(VM& vm, Program const& pr } // 12. Let declaredVarNames be a new empty List. - HashTable declared_var_names; + HashTable declared_var_names; // 13. For each element d of varDeclarations, do TRY(program.for_each_var_scoped_variable_declaration([&](VariableDeclaration const& declaration) { @@ -1109,7 +1109,7 @@ Object* create_mapped_arguments_object(VM& vm, FunctionObject& function, Vector< MUST(object->define_property_or_throw(vm.names.length, { .value = Value(length), .writable = true, .enumerable = false, .configurable = true })); // 17. Let mappedNames be a new empty List. - HashTable mapped_names; + HashTable mapped_names; // 18. Set index to numberOfParameters - 1. // 19. Repeat, while index ≥ 0, @@ -1178,19 +1178,21 @@ CanonicalIndex canonical_numeric_index_string(PropertyKey const& property_key, C if (argument.is_empty()) return CanonicalIndex(CanonicalIndex::Type::Undefined, 0); u32 current_index = 0; - if (argument.characters()[current_index] == '-') { + auto const* characters = argument.bytes_as_string_view().characters_without_null_termination(); + auto const length = argument.bytes_as_string_view().length(); + if (characters[current_index] == '-') { current_index++; - if (current_index == argument.length()) + if (current_index == length) return CanonicalIndex(CanonicalIndex::Type::Undefined, 0); } - if (argument.characters()[current_index] == '0') { + if (characters[current_index] == '0') { current_index++; - if (current_index == argument.length()) + if (current_index == length) return CanonicalIndex(CanonicalIndex::Type::Numeric, 0); - if (argument.characters()[current_index] != '.') + if (characters[current_index] != '.') return CanonicalIndex(CanonicalIndex::Type::Undefined, 0); current_index++; - if (current_index == argument.length()) + if (current_index == length) return CanonicalIndex(CanonicalIndex::Type::Undefined, 0); } @@ -1199,17 +1201,17 @@ CanonicalIndex canonical_numeric_index_string(PropertyKey const& property_key, C return CanonicalIndex(CanonicalIndex::Type::Numeric, 0); // Short circuit any string that doesn't start with digits - if (char first_non_zero = argument.characters()[current_index]; first_non_zero < '0' || first_non_zero > '9') + if (char first_non_zero = characters[current_index]; first_non_zero < '0' || first_non_zero > '9') return CanonicalIndex(CanonicalIndex::Type::Undefined, 0); // 2. Let n be ! ToNumber(argument). - auto maybe_double = argument.to_number(AK::TrimWhitespace::No); + auto maybe_double = argument.bytes_as_string_view().to_number(AK::TrimWhitespace::No); if (!maybe_double.has_value()) return CanonicalIndex(CanonicalIndex::Type::Undefined, 0); // FIXME: We return 0 instead of n but it might not observable? // 3. If SameValue(! ToString(n), argument) is true, return n. - if (number_to_string(*maybe_double) == argument.view()) + if (number_to_string(*maybe_double) == argument) return CanonicalIndex(CanonicalIndex::Type::Numeric, 0); // 4. Return undefined. @@ -1724,7 +1726,7 @@ ThrowCompletionOr perform_import_call(VM& vm, Value specifier, Value opti // 8. Let specifierString be Completion(ToString(specifier)). // 9. IfAbruptRejectPromise(specifierString, promiseCapability). - auto specifier_string = TRY_OR_REJECT_WITH_VALUE(vm, promise_capability, specifier.to_byte_string(vm)); + auto specifier_string = TRY_OR_REJECT_WITH_VALUE(vm, promise_capability, specifier.to_string(vm)); // 10. Let attributes be a new empty List. Vector attributes; @@ -1780,7 +1782,7 @@ ThrowCompletionOr perform_import_call(VM& vm, Value specifier, Value opti } // 4. Append the ImportAttribute Record { [[Key]]: key, [[Value]]: value } to attributes. - attributes.empend(key.as_string().byte_string(), value.as_string().byte_string()); + attributes.empend(key.as_string().utf8_string(), value.as_string().utf8_string()); } } diff --git a/Libraries/LibJS/Runtime/AbstractOperations.h b/Libraries/LibJS/Runtime/AbstractOperations.h index 2bb1a0ef3ef..68847e7c869 100644 --- a/Libraries/LibJS/Runtime/AbstractOperations.h +++ b/Libraries/LibJS/Runtime/AbstractOperations.h @@ -38,7 +38,7 @@ ThrowCompletionOr length_of_array_like(VM&, Object const&); ThrowCompletionOr> create_list_from_array_like(VM&, Value, Function(Value)> = {}); ThrowCompletionOr species_constructor(VM&, Object const&, FunctionObject& default_constructor); ThrowCompletionOr get_function_realm(VM&, FunctionObject const&); -ThrowCompletionOr initialize_bound_name(VM&, DeprecatedFlyString const&, Value, Environment*); +ThrowCompletionOr initialize_bound_name(VM&, FlyString const&, Value, Environment*); bool is_compatible_property_descriptor(bool extensible, PropertyDescriptor const&, Optional const& current); bool validate_and_apply_property_descriptor(Object*, PropertyKey const&, bool extensible, PropertyDescriptor const&, Optional const& current); ThrowCompletionOr get_prototype_from_constructor(VM&, FunctionObject const& constructor, GC::Ref (Intrinsics::*intrinsic_default_prototype)()); diff --git a/Libraries/LibJS/Runtime/BoundFunction.cpp b/Libraries/LibJS/Runtime/BoundFunction.cpp index 723e19688c0..0f799289b34 100644 --- a/Libraries/LibJS/Runtime/BoundFunction.cpp +++ b/Libraries/LibJS/Runtime/BoundFunction.cpp @@ -40,7 +40,7 @@ BoundFunction::BoundFunction(Realm& realm, FunctionObject& bound_target_function , m_bound_this(bound_this) , m_bound_arguments(move(bound_arguments)) // FIXME: Non-standard and redundant, remove. - , m_name(ByteString::formatted("bound {}", bound_target_function.name())) + , m_name(MUST(String::formatted("bound {}", bound_target_function.name()))) { } diff --git a/Libraries/LibJS/Runtime/BoundFunction.h b/Libraries/LibJS/Runtime/BoundFunction.h index 50f9e0353dd..7c48ebf4eed 100644 --- a/Libraries/LibJS/Runtime/BoundFunction.h +++ b/Libraries/LibJS/Runtime/BoundFunction.h @@ -23,7 +23,7 @@ public: virtual ThrowCompletionOr internal_call(Value this_argument, ReadonlySpan arguments_list) override; virtual ThrowCompletionOr> internal_construct(ReadonlySpan arguments_list, FunctionObject& new_target) override; - virtual DeprecatedFlyString const& name() const override { return m_name; } + virtual FlyString const& name() const override { return m_name; } virtual bool is_strict_mode() const override { return m_bound_target_function->is_strict_mode(); } virtual bool has_constructor() const override { return m_bound_target_function->has_constructor(); } @@ -40,7 +40,7 @@ private: Value m_bound_this; // [[BoundThis]] Vector m_bound_arguments; // [[BoundArguments]] - DeprecatedFlyString m_name; + FlyString m_name; }; } diff --git a/Libraries/LibJS/Runtime/CommonPropertyNames.h b/Libraries/LibJS/Runtime/CommonPropertyNames.h index cbc0c874d9c..b03b57b111b 100644 --- a/Libraries/LibJS/Runtime/CommonPropertyNames.h +++ b/Libraries/LibJS/Runtime/CommonPropertyNames.h @@ -608,35 +608,35 @@ namespace JS { P(zonedDateTimeISO) struct CommonPropertyNames { - PropertyKey and_ { "and", PropertyKey::StringMayBeNumber::No }; - PropertyKey catch_ { "catch", PropertyKey::StringMayBeNumber::No }; - PropertyKey delete_ { "delete", PropertyKey::StringMayBeNumber::No }; - PropertyKey for_ { "for", PropertyKey::StringMayBeNumber::No }; - PropertyKey or_ { "or", PropertyKey::StringMayBeNumber::No }; - PropertyKey register_ { "register", PropertyKey::StringMayBeNumber::No }; - PropertyKey return_ { "return", PropertyKey::StringMayBeNumber::No }; - PropertyKey throw_ { "throw", PropertyKey::StringMayBeNumber::No }; - PropertyKey try_ { "try", PropertyKey::StringMayBeNumber::No }; - PropertyKey union_ { "union", PropertyKey::StringMayBeNumber::No }; - PropertyKey xor_ { "xor", PropertyKey::StringMayBeNumber::No }; - PropertyKey inputAlias { "$_", PropertyKey::StringMayBeNumber::No }; - PropertyKey lastMatchAlias { "$&", PropertyKey::StringMayBeNumber::No }; - PropertyKey lastParenAlias { "$+", PropertyKey::StringMayBeNumber::No }; - PropertyKey leftContextAlias { "$`", PropertyKey::StringMayBeNumber::No }; - PropertyKey rightContextAlias { "$'", PropertyKey::StringMayBeNumber::No }; -#define __ENUMERATE(x) PropertyKey x { #x, PropertyKey::StringMayBeNumber::No }; + PropertyKey and_ { "and"_fly_string, PropertyKey::StringMayBeNumber::No }; + PropertyKey catch_ { "catch"_fly_string, PropertyKey::StringMayBeNumber::No }; + PropertyKey delete_ { "delete"_fly_string, PropertyKey::StringMayBeNumber::No }; + PropertyKey for_ { "for"_fly_string, PropertyKey::StringMayBeNumber::No }; + PropertyKey or_ { "or"_fly_string, PropertyKey::StringMayBeNumber::No }; + PropertyKey register_ { "register"_fly_string, PropertyKey::StringMayBeNumber::No }; + PropertyKey return_ { "return"_fly_string, PropertyKey::StringMayBeNumber::No }; + PropertyKey throw_ { "throw"_fly_string, PropertyKey::StringMayBeNumber::No }; + PropertyKey try_ { "try"_fly_string, PropertyKey::StringMayBeNumber::No }; + PropertyKey union_ { "union"_fly_string, PropertyKey::StringMayBeNumber::No }; + PropertyKey xor_ { "xor"_fly_string, PropertyKey::StringMayBeNumber::No }; + PropertyKey inputAlias { "$_"_fly_string, PropertyKey::StringMayBeNumber::No }; + PropertyKey lastMatchAlias { "$&"_fly_string, PropertyKey::StringMayBeNumber::No }; + PropertyKey lastParenAlias { "$+"_fly_string, PropertyKey::StringMayBeNumber::No }; + PropertyKey leftContextAlias { "$`"_fly_string, PropertyKey::StringMayBeNumber::No }; + PropertyKey rightContextAlias { "$'"_fly_string, PropertyKey::StringMayBeNumber::No }; +#define __ENUMERATE(x) PropertyKey x { #x##_fly_string, PropertyKey::StringMayBeNumber::No }; ENUMERATE_STANDARD_PROPERTY_NAMES(__ENUMERATE) #undef __ENUMERATE -#define __JS_ENUMERATE(x, a, b, c, t) PropertyKey x { #x, PropertyKey::StringMayBeNumber::No }; +#define __JS_ENUMERATE(x, a, b, c, t) PropertyKey x { #x##_fly_string, PropertyKey::StringMayBeNumber::No }; JS_ENUMERATE_BUILTIN_TYPES #undef __JS_ENUMERATE -#define __JS_ENUMERATE(x, a, b, c) PropertyKey x { #x, PropertyKey::StringMayBeNumber::No }; +#define __JS_ENUMERATE(x, a, b, c) PropertyKey x { #x##_fly_string, PropertyKey::StringMayBeNumber::No }; JS_ENUMERATE_INTL_OBJECTS #undef __JS_ENUMERATE -#define __JS_ENUMERATE(x, a, b, c) PropertyKey x { #x, PropertyKey::StringMayBeNumber::No }; +#define __JS_ENUMERATE(x, a, b, c) PropertyKey x { #x##_fly_string, PropertyKey::StringMayBeNumber::No }; JS_ENUMERATE_TEMPORAL_OBJECTS #undef __JS_ENUMERATE -#define __JS_ENUMERATE(x, a) PropertyKey x { #x, PropertyKey::StringMayBeNumber::No }; +#define __JS_ENUMERATE(x, a) PropertyKey x { #x##_fly_string, PropertyKey::StringMayBeNumber::No }; JS_ENUMERATE_WELL_KNOWN_SYMBOLS #undef __JS_ENUMERATE }; diff --git a/Libraries/LibJS/Runtime/DeclarativeEnvironment.cpp b/Libraries/LibJS/Runtime/DeclarativeEnvironment.cpp index 4a7b0ceb01c..d17141b1ed5 100644 --- a/Libraries/LibJS/Runtime/DeclarativeEnvironment.cpp +++ b/Libraries/LibJS/Runtime/DeclarativeEnvironment.cpp @@ -52,7 +52,7 @@ void DeclarativeEnvironment::visit_edges(Visitor& visitor) } // 9.1.1.1.1 HasBinding ( N ), https://tc39.es/ecma262/#sec-declarative-environment-records-hasbinding-n -ThrowCompletionOr DeclarativeEnvironment::has_binding(DeprecatedFlyString const& name, Optional* out_index) const +ThrowCompletionOr DeclarativeEnvironment::has_binding(FlyString const& name, Optional* out_index) const { auto binding_and_index = find_binding_and_index(name); if (!binding_and_index.has_value()) @@ -63,7 +63,7 @@ ThrowCompletionOr DeclarativeEnvironment::has_binding(DeprecatedFlyString } // 9.1.1.1.2 CreateMutableBinding ( N, D ), https://tc39.es/ecma262/#sec-declarative-environment-records-createmutablebinding-n-d -ThrowCompletionOr DeclarativeEnvironment::create_mutable_binding(VM&, DeprecatedFlyString const& name, bool can_be_deleted) +ThrowCompletionOr DeclarativeEnvironment::create_mutable_binding(VM&, FlyString const& name, bool can_be_deleted) { // 1. Assert: envRec does not already have a binding for N. // NOTE: We skip this to avoid O(n) traversal of m_bindings. @@ -86,7 +86,7 @@ ThrowCompletionOr DeclarativeEnvironment::create_mutable_binding(VM&, Depr } // 9.1.1.1.3 CreateImmutableBinding ( N, S ), https://tc39.es/ecma262/#sec-declarative-environment-records-createimmutablebinding-n-s -ThrowCompletionOr DeclarativeEnvironment::create_immutable_binding(VM&, DeprecatedFlyString const& name, bool strict) +ThrowCompletionOr DeclarativeEnvironment::create_immutable_binding(VM&, FlyString const& name, bool strict) { // 1. Assert: envRec does not already have a binding for N. // NOTE: We skip this to avoid O(n) traversal of m_bindings. @@ -110,7 +110,7 @@ ThrowCompletionOr DeclarativeEnvironment::create_immutable_binding(VM&, De // 9.1.1.1.4 InitializeBinding ( N, V ), https://tc39.es/ecma262/#sec-declarative-environment-records-initializebinding-n-v // 4.1.1.1.1 InitializeBinding ( N, V, hint ), https://tc39.es/proposal-explicit-resource-management/#sec-declarative-environment-records -ThrowCompletionOr DeclarativeEnvironment::initialize_binding(VM& vm, DeprecatedFlyString const& name, Value value, Environment::InitializeBindingHint hint) +ThrowCompletionOr DeclarativeEnvironment::initialize_binding(VM& vm, FlyString const& name, Value value, Environment::InitializeBindingHint hint) { return initialize_binding_direct(vm, find_binding_and_index(name)->index().value(), value, hint); } @@ -137,7 +137,7 @@ ThrowCompletionOr DeclarativeEnvironment::initialize_binding_direct(VM& vm } // 9.1.1.1.5 SetMutableBinding ( N, V, S ), https://tc39.es/ecma262/#sec-declarative-environment-records-setmutablebinding-n-v-s -ThrowCompletionOr DeclarativeEnvironment::set_mutable_binding(VM& vm, DeprecatedFlyString const& name, Value value, bool strict) +ThrowCompletionOr DeclarativeEnvironment::set_mutable_binding(VM& vm, FlyString const& name, Value value, bool strict) { // 1. If envRec does not have a binding for N, then auto binding_and_index = find_binding_and_index(name); @@ -187,7 +187,7 @@ ThrowCompletionOr DeclarativeEnvironment::set_mutable_binding_direct(VM& v } // 9.1.1.1.6 GetBindingValue ( N, S ), https://tc39.es/ecma262/#sec-declarative-environment-records-getbindingvalue-n-s -ThrowCompletionOr DeclarativeEnvironment::get_binding_value(VM& vm, DeprecatedFlyString const& name, [[maybe_unused]] bool strict) +ThrowCompletionOr DeclarativeEnvironment::get_binding_value(VM& vm, FlyString const& name, [[maybe_unused]] bool strict) { // 1. Assert: envRec has a binding for N. auto binding_and_index = find_binding_and_index(name); @@ -198,7 +198,7 @@ ThrowCompletionOr DeclarativeEnvironment::get_binding_value(VM& vm, Depre } // 9.1.1.1.7 DeleteBinding ( N ), https://tc39.es/ecma262/#sec-declarative-environment-records-deletebinding-n -ThrowCompletionOr DeclarativeEnvironment::delete_binding(VM&, DeprecatedFlyString const& name) +ThrowCompletionOr DeclarativeEnvironment::delete_binding(VM&, FlyString const& name) { // 1. Assert: envRec has a binding for the name that is the value of N. auto binding_and_index = find_binding_and_index(name); @@ -218,7 +218,7 @@ ThrowCompletionOr DeclarativeEnvironment::delete_binding(VM&, DeprecatedFl return true; } -ThrowCompletionOr DeclarativeEnvironment::initialize_or_set_mutable_binding(VM& vm, DeprecatedFlyString const& name, Value value) +ThrowCompletionOr DeclarativeEnvironment::initialize_or_set_mutable_binding(VM& vm, FlyString const& name, Value value) { auto binding_and_index = find_binding_and_index(name); VERIFY(binding_and_index.has_value()); @@ -230,7 +230,7 @@ ThrowCompletionOr DeclarativeEnvironment::initialize_or_set_mutable_bindin return {}; } -void DeclarativeEnvironment::initialize_or_set_mutable_binding(Badge, VM& vm, DeprecatedFlyString const& name, Value value) +void DeclarativeEnvironment::initialize_or_set_mutable_binding(Badge, VM& vm, FlyString const& name, Value value) { MUST(initialize_or_set_mutable_binding(vm, name, value)); } diff --git a/Libraries/LibJS/Runtime/DeclarativeEnvironment.h b/Libraries/LibJS/Runtime/DeclarativeEnvironment.h index 96adb668931..722811b14db 100644 --- a/Libraries/LibJS/Runtime/DeclarativeEnvironment.h +++ b/Libraries/LibJS/Runtime/DeclarativeEnvironment.h @@ -6,7 +6,7 @@ #pragma once -#include +#include #include #include #include @@ -20,7 +20,7 @@ class DeclarativeEnvironment : public Environment { GC_DECLARE_ALLOCATOR(DeclarativeEnvironment); struct Binding { - DeprecatedFlyString name; + FlyString name; Value value; bool strict { false }; bool mutable_ { false }; @@ -33,21 +33,21 @@ public: virtual ~DeclarativeEnvironment() override = default; - virtual ThrowCompletionOr has_binding(DeprecatedFlyString const& name, Optional* = nullptr) const override final; - virtual ThrowCompletionOr create_mutable_binding(VM&, DeprecatedFlyString const& name, bool can_be_deleted) override final; - virtual ThrowCompletionOr create_immutable_binding(VM&, DeprecatedFlyString const& name, bool strict) override final; - virtual ThrowCompletionOr initialize_binding(VM&, DeprecatedFlyString const& name, Value, InitializeBindingHint) override final; - virtual ThrowCompletionOr set_mutable_binding(VM&, DeprecatedFlyString const& name, Value, bool strict) override final; - virtual ThrowCompletionOr get_binding_value(VM&, DeprecatedFlyString const& name, bool strict) override; - virtual ThrowCompletionOr delete_binding(VM&, DeprecatedFlyString const& name) override; + virtual ThrowCompletionOr has_binding(FlyString const& name, Optional* = nullptr) const override final; + virtual ThrowCompletionOr create_mutable_binding(VM&, FlyString const& name, bool can_be_deleted) override final; + virtual ThrowCompletionOr create_immutable_binding(VM&, FlyString const& name, bool strict) override final; + virtual ThrowCompletionOr initialize_binding(VM&, FlyString const& name, Value, InitializeBindingHint) override final; + virtual ThrowCompletionOr set_mutable_binding(VM&, FlyString const& name, Value, bool strict) override final; + virtual ThrowCompletionOr get_binding_value(VM&, FlyString const& name, bool strict) override; + virtual ThrowCompletionOr delete_binding(VM&, FlyString const& name) override; - void initialize_or_set_mutable_binding(Badge, VM&, DeprecatedFlyString const& name, Value value); - ThrowCompletionOr initialize_or_set_mutable_binding(VM&, DeprecatedFlyString const& name, Value value); + void initialize_or_set_mutable_binding(Badge, VM&, FlyString const& name, Value value); + ThrowCompletionOr initialize_or_set_mutable_binding(VM&, FlyString const& name, Value value); // This is not a method defined in the spec! Do not use this in any LibJS (or other spec related) code. - [[nodiscard]] Vector bindings() const + [[nodiscard]] Vector bindings() const { - Vector names; + Vector names; names.ensure_capacity(m_bindings.size()); for (auto const& binding : m_bindings) @@ -113,7 +113,7 @@ protected: friend class ModuleEnvironment; - virtual Optional find_binding_and_index(DeprecatedFlyString const& name) const + virtual Optional find_binding_and_index(FlyString const& name) const { if (auto it = m_bindings_assoc.find(name); it != m_bindings_assoc.end()) { return BindingAndIndex { const_cast(&m_bindings.at(it->value)), it->value }; @@ -124,7 +124,7 @@ protected: private: Vector m_bindings; - HashMap m_bindings_assoc; + HashMap m_bindings_assoc; DisposeCapability m_dispose_capability; u64 m_environment_serial_number { 0 }; diff --git a/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp b/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp index ac61bfc35fa..01a9eed4b87 100644 --- a/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp +++ b/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp @@ -33,7 +33,7 @@ namespace JS { GC_DEFINE_ALLOCATOR(ECMAScriptFunctionObject); -GC::Ref ECMAScriptFunctionObject::create(Realm& realm, DeprecatedFlyString name, ByteString source_text, Statement const& ecmascript_code, Vector parameters, i32 m_function_length, Vector local_variables_names, Environment* parent_environment, PrivateEnvironment* private_environment, FunctionKind kind, bool is_strict, FunctionParsingInsights parsing_insights, bool is_arrow_function, Variant class_field_initializer_name) +GC::Ref ECMAScriptFunctionObject::create(Realm& realm, FlyString name, ByteString source_text, Statement const& ecmascript_code, Vector parameters, i32 m_function_length, Vector local_variables_names, Environment* parent_environment, PrivateEnvironment* private_environment, FunctionKind kind, bool is_strict, FunctionParsingInsights parsing_insights, bool is_arrow_function, Variant class_field_initializer_name) { Object* prototype = nullptr; switch (kind) { @@ -53,12 +53,12 @@ GC::Ref ECMAScriptFunctionObject::create(Realm& realm, return realm.create(move(name), move(source_text), ecmascript_code, move(parameters), m_function_length, move(local_variables_names), parent_environment, private_environment, *prototype, kind, is_strict, parsing_insights, is_arrow_function, move(class_field_initializer_name)); } -GC::Ref ECMAScriptFunctionObject::create(Realm& realm, DeprecatedFlyString name, Object& prototype, ByteString source_text, Statement const& ecmascript_code, Vector parameters, i32 m_function_length, Vector local_variables_names, Environment* parent_environment, PrivateEnvironment* private_environment, FunctionKind kind, bool is_strict, FunctionParsingInsights parsing_insights, bool is_arrow_function, Variant class_field_initializer_name) +GC::Ref ECMAScriptFunctionObject::create(Realm& realm, FlyString name, Object& prototype, ByteString source_text, Statement const& ecmascript_code, Vector parameters, i32 m_function_length, Vector local_variables_names, Environment* parent_environment, PrivateEnvironment* private_environment, FunctionKind kind, bool is_strict, FunctionParsingInsights parsing_insights, bool is_arrow_function, Variant class_field_initializer_name) { return realm.create(move(name), move(source_text), ecmascript_code, move(parameters), m_function_length, move(local_variables_names), parent_environment, private_environment, prototype, kind, is_strict, parsing_insights, is_arrow_function, move(class_field_initializer_name)); } -ECMAScriptFunctionObject::ECMAScriptFunctionObject(DeprecatedFlyString name, ByteString source_text, Statement const& ecmascript_code, Vector formal_parameters, i32 function_length, Vector local_variables_names, Environment* parent_environment, PrivateEnvironment* private_environment, Object& prototype, FunctionKind kind, bool strict, FunctionParsingInsights parsing_insights, bool is_arrow_function, Variant class_field_initializer_name) +ECMAScriptFunctionObject::ECMAScriptFunctionObject(FlyString name, ByteString source_text, Statement const& ecmascript_code, Vector formal_parameters, i32 function_length, Vector local_variables_names, Environment* parent_environment, PrivateEnvironment* private_environment, Object& prototype, FunctionKind kind, bool strict, FunctionParsingInsights parsing_insights, bool is_arrow_function, Variant class_field_initializer_name) : FunctionObject(prototype) , m_name(move(name)) , m_function_length(function_length) @@ -161,7 +161,7 @@ ECMAScriptFunctionObject::ECMAScriptFunctionObject(DeprecatedFlyString name, Byt m_arguments_object_needed = false; } - HashTable function_names; + HashTable function_names; // 18. Else if hasParameterExpressions is false, then // a. If functionNames contains "arguments" or lexicalNames contains "arguments", then @@ -210,7 +210,7 @@ ECMAScriptFunctionObject::ECMAScriptFunctionObject(DeprecatedFlyString name, Byt *environment_size += parameters_in_environment; - HashMap parameter_bindings; + HashMap parameter_bindings; auto arguments_object_needs_binding = m_arguments_object_needed && !m_local_variables_names.contains_slow(vm().names.arguments.as_string()); @@ -227,7 +227,7 @@ ECMAScriptFunctionObject::ECMAScriptFunctionObject(DeprecatedFlyString name, Byt // a. Let parameterBindings be parameterNames. } - HashMap instantiated_var_names; + HashMap instantiated_var_names; size_t* var_environment_size = nullptr; @@ -721,7 +721,7 @@ void async_block_start(VM& vm, T const& async_body, PromiseCapability const& pro auto& running_context = vm.running_execution_context(); // 2. Let closure be a new Abstract Closure with no parameters that captures promiseCapability and asyncBody and performs the following steps when called: - auto closure = NativeFunction::create(realm, "", [&async_body, &promise_capability](auto& vm) -> ThrowCompletionOr { + auto closure = NativeFunction::create(realm, ""_fly_string, [&async_body, &promise_capability](auto& vm) -> ThrowCompletionOr { Completion result; // a. Let acAsyncContext be the running execution context. @@ -729,7 +729,7 @@ void async_block_start(VM& vm, T const& async_body, PromiseCapability const& pro // b. If asyncBody is a Parse Node, then if constexpr (!IsSame>) { // i. Let result be Completion(Evaluation of asyncBody). - auto maybe_executable = Bytecode::compile(vm, async_body, FunctionKind::Async, "AsyncBlockStart"sv); + auto maybe_executable = Bytecode::compile(vm, async_body, FunctionKind::Async, "AsyncBlockStart"_fly_string); if (maybe_executable.is_error()) result = maybe_executable.release_error(); else @@ -840,7 +840,7 @@ Completion ECMAScriptFunctionObject::ordinary_call_evaluate_body() return { Completion::Type::Return, generator_object }; } -void ECMAScriptFunctionObject::set_name(DeprecatedFlyString const& name) +void ECMAScriptFunctionObject::set_name(FlyString const& name) { auto& vm = this->vm(); m_name = name; diff --git a/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.h b/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.h index 0c876f75d9e..9cd46617883 100644 --- a/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.h +++ b/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.h @@ -39,8 +39,8 @@ public: Global, }; - static GC::Ref create(Realm&, DeprecatedFlyString name, ByteString source_text, Statement const& ecmascript_code, Vector parameters, i32 m_function_length, Vector local_variables_names, Environment* parent_environment, PrivateEnvironment* private_environment, FunctionKind, bool is_strict, FunctionParsingInsights, bool is_arrow_function = false, Variant class_field_initializer_name = {}); - static GC::Ref create(Realm&, DeprecatedFlyString name, Object& prototype, ByteString source_text, Statement const& ecmascript_code, Vector parameters, i32 m_function_length, Vector local_variables_names, Environment* parent_environment, PrivateEnvironment* private_environment, FunctionKind, bool is_strict, FunctionParsingInsights, bool is_arrow_function = false, Variant class_field_initializer_name = {}); + static GC::Ref create(Realm&, FlyString name, ByteString source_text, Statement const& ecmascript_code, Vector parameters, i32 m_function_length, Vector local_variables_names, Environment* parent_environment, PrivateEnvironment* private_environment, FunctionKind, bool is_strict, FunctionParsingInsights, bool is_arrow_function = false, Variant class_field_initializer_name = {}); + static GC::Ref create(Realm&, FlyString name, Object& prototype, ByteString source_text, Statement const& ecmascript_code, Vector parameters, i32 m_function_length, Vector local_variables_names, Environment* parent_environment, PrivateEnvironment* private_environment, FunctionKind, bool is_strict, FunctionParsingInsights, bool is_arrow_function = false, Variant class_field_initializer_name = {}); virtual void initialize(Realm&) override; virtual ~ECMAScriptFunctionObject() override = default; @@ -56,8 +56,8 @@ public: Statement const& ecmascript_code() const { return m_ecmascript_code; } Vector const& formal_parameters() const override { return m_formal_parameters; } - virtual DeprecatedFlyString const& name() const override { return m_name; } - void set_name(DeprecatedFlyString const& name); + virtual FlyString const& name() const override { return m_name; } + void set_name(FlyString const& name); void set_is_class_constructor() { m_is_class_constructor = true; } @@ -89,7 +89,7 @@ public: // Equivalent to absence of [[Construct]] virtual bool has_constructor() const override { return m_kind == FunctionKind::Normal && !m_is_arrow_function; } - virtual Vector const& local_variables_names() const override { return m_local_variables_names; } + virtual Vector const& local_variables_names() const override { return m_local_variables_names; } FunctionKind kind() const { return m_kind; } @@ -109,7 +109,7 @@ protected: virtual Completion ordinary_call_evaluate_body(); private: - ECMAScriptFunctionObject(DeprecatedFlyString name, ByteString source_text, Statement const& ecmascript_code, Vector parameters, i32 m_function_length, Vector local_variables_names, Environment* parent_environment, PrivateEnvironment* private_environment, Object& prototype, FunctionKind, bool is_strict, FunctionParsingInsights, bool is_arrow_function, Variant class_field_initializer_name); + ECMAScriptFunctionObject(FlyString name, ByteString source_text, Statement const& ecmascript_code, Vector parameters, i32 m_function_length, Vector local_variables_names, Environment* parent_environment, PrivateEnvironment* private_environment, Object& prototype, FunctionKind, bool is_strict, FunctionParsingInsights, bool is_arrow_function, Variant class_field_initializer_name); virtual bool is_ecmascript_function_object() const override { return true; } virtual void visit_edges(Visitor&) override; @@ -117,12 +117,12 @@ private: ThrowCompletionOr prepare_for_ordinary_call(ExecutionContext& callee_context, Object* new_target); void ordinary_call_bind_this(ExecutionContext&, Value this_argument); - DeprecatedFlyString m_name; + FlyString m_name; GC::Ptr m_name_string; GC::Ptr m_bytecode_executable; i32 m_function_length { 0 }; - Vector m_local_variables_names; + Vector m_local_variables_names; // Internal Slots of ECMAScript Function Objects, https://tc39.es/ecma262/#table-internal-slots-of-ecmascript-function-objects GC::Ptr m_environment; // [[Environment]] @@ -159,14 +159,14 @@ private: No, Yes, }; - HashMap m_parameter_names; + HashMap m_parameter_names; Vector m_functions_to_initialize; bool m_arguments_object_needed { false }; bool m_is_module_wrapper { false }; bool m_function_environment_needed { false }; bool m_uses_this { false }; Vector m_var_names_to_initialize_binding; - Vector m_function_names_to_initialize_binding; + Vector m_function_names_to_initialize_binding; size_t m_function_environment_bindings_count { 0 }; size_t m_var_environment_bindings_count { 0 }; diff --git a/Libraries/LibJS/Runtime/Environment.h b/Libraries/LibJS/Runtime/Environment.h index 5af506897b8..a43f97caef0 100644 --- a/Libraries/LibJS/Runtime/Environment.h +++ b/Libraries/LibJS/Runtime/Environment.h @@ -34,13 +34,13 @@ public: virtual Object* with_base_object() const { return nullptr; } - virtual ThrowCompletionOr has_binding([[maybe_unused]] DeprecatedFlyString const& name, [[maybe_unused]] Optional* out_index = nullptr) const { return false; } - virtual ThrowCompletionOr create_mutable_binding(VM&, [[maybe_unused]] DeprecatedFlyString const& name, [[maybe_unused]] bool can_be_deleted) { return {}; } - virtual ThrowCompletionOr create_immutable_binding(VM&, [[maybe_unused]] DeprecatedFlyString const& name, [[maybe_unused]] bool strict) { return {}; } - virtual ThrowCompletionOr initialize_binding(VM&, [[maybe_unused]] DeprecatedFlyString const& name, Value, InitializeBindingHint) { return {}; } - virtual ThrowCompletionOr set_mutable_binding(VM&, [[maybe_unused]] DeprecatedFlyString const& name, Value, [[maybe_unused]] bool strict) { return {}; } - virtual ThrowCompletionOr get_binding_value(VM&, [[maybe_unused]] DeprecatedFlyString const& name, [[maybe_unused]] bool strict) { return Value {}; } - virtual ThrowCompletionOr delete_binding(VM&, [[maybe_unused]] DeprecatedFlyString const& name) { return false; } + virtual ThrowCompletionOr has_binding([[maybe_unused]] FlyString const& name, [[maybe_unused]] Optional* out_index = nullptr) const { return false; } + virtual ThrowCompletionOr create_mutable_binding(VM&, [[maybe_unused]] FlyString const& name, [[maybe_unused]] bool can_be_deleted) { return {}; } + virtual ThrowCompletionOr create_immutable_binding(VM&, [[maybe_unused]] FlyString const& name, [[maybe_unused]] bool strict) { return {}; } + virtual ThrowCompletionOr initialize_binding(VM&, [[maybe_unused]] FlyString const& name, Value, InitializeBindingHint) { return {}; } + virtual ThrowCompletionOr set_mutable_binding(VM&, [[maybe_unused]] FlyString const& name, Value, [[maybe_unused]] bool strict) { return {}; } + virtual ThrowCompletionOr get_binding_value(VM&, [[maybe_unused]] FlyString const& name, [[maybe_unused]] bool strict) { return Value {}; } + virtual ThrowCompletionOr delete_binding(VM&, [[maybe_unused]] FlyString const& name) { return false; } // [[OuterEnv]] Environment* outer_environment() { return m_outer_environment; } diff --git a/Libraries/LibJS/Runtime/Error.cpp b/Libraries/LibJS/Runtime/Error.cpp index 69b1b1f0b90..e27b32bae1c 100644 --- a/Libraries/LibJS/Runtime/Error.cpp +++ b/Libraries/LibJS/Runtime/Error.cpp @@ -84,7 +84,7 @@ void Error::populate_stack() for (auto& element : stack_trace) { auto* context = element.execution_context; TracebackFrame frame { - .function_name = context->function_name ? context->function_name->byte_string() : "", + .function_name = context->function_name ? context->function_name->utf8_string() : ""_string, .cached_source_range = element.source_range, }; @@ -111,7 +111,7 @@ String Error::stack_string(CompactTraceback compact) const else stack_string_builder.appendff(" at {} ({}:{}:{})\n", function_name, source_range.filename(), source_range.start.line, source_range.start.column); } else { - stack_string_builder.appendff(" at {}\n", function_name.is_empty() ? ""sv : function_name.view()); + stack_string_builder.appendff(" at {}\n", function_name.is_empty() ? ""sv : function_name); } }; diff --git a/Libraries/LibJS/Runtime/Error.h b/Libraries/LibJS/Runtime/Error.h index e28868f9474..b63befc3570 100644 --- a/Libraries/LibJS/Runtime/Error.h +++ b/Libraries/LibJS/Runtime/Error.h @@ -7,7 +7,6 @@ #pragma once -#include #include #include #include @@ -16,7 +15,7 @@ namespace JS { struct TracebackFrame { - DeprecatedFlyString function_name; + FlyString function_name; [[nodiscard]] SourceRange const& source_range() const; RefPtr cached_source_range; diff --git a/Libraries/LibJS/Runtime/ErrorTypes.h b/Libraries/LibJS/Runtime/ErrorTypes.h index 9322c58c76f..7021bf3634f 100644 --- a/Libraries/LibJS/Runtime/ErrorTypes.h +++ b/Libraries/LibJS/Runtime/ErrorTypes.h @@ -6,6 +6,7 @@ #pragma once +#include #include #define JS_ENUMERATE_ERROR_TYPES(M) \ @@ -309,18 +310,18 @@ public: JS_ENUMERATE_ERROR_TYPES(__ENUMERATE_JS_ERROR) #undef __ENUMERATE_JS_ERROR - StringView message() const + String message() const { return m_message; } private: explicit ErrorType(StringView message) - : m_message(message) + : m_message(MUST(String::from_utf8(message))) { } - StringView m_message; + String m_message; }; } diff --git a/Libraries/LibJS/Runtime/FunctionConstructor.cpp b/Libraries/LibJS/Runtime/FunctionConstructor.cpp index 4db94b25c7b..33780d59934 100644 --- a/Libraries/LibJS/Runtime/FunctionConstructor.cpp +++ b/Libraries/LibJS/Runtime/FunctionConstructor.cpp @@ -218,7 +218,7 @@ ThrowCompletionOr> FunctionConstructor::create // 28. Let F be OrdinaryFunctionCreate(proto, sourceText, parameters, body, non-lexical-this, env, privateEnv). parsing_insights.might_need_arguments_object = true; - auto function = ECMAScriptFunctionObject::create(realm, "anonymous", *prototype, move(source_text), expr->body(), expr->parameters(), expr->function_length(), expr->local_variables_names(), &environment, private_environment, expr->kind(), expr->is_strict_mode(), parsing_insights); + auto function = ECMAScriptFunctionObject::create(realm, "anonymous"_fly_string, *prototype, move(source_text), expr->body(), expr->parameters(), expr->function_length(), expr->local_variables_names(), &environment, private_environment, expr->kind(), expr->is_strict_mode(), parsing_insights); // FIXME: Remove the name argument from create() and do this instead. // 29. Perform SetFunctionName(F, "anonymous"). diff --git a/Libraries/LibJS/Runtime/FunctionObject.cpp b/Libraries/LibJS/Runtime/FunctionObject.cpp index ee9527d2143..73614f60e84 100644 --- a/Libraries/LibJS/Runtime/FunctionObject.cpp +++ b/Libraries/LibJS/Runtime/FunctionObject.cpp @@ -32,7 +32,7 @@ void FunctionObject::set_function_name(Variant const& VERIFY(m_is_extensible); VERIFY(!storage_has(vm.names.name)); - ByteString name; + String name; // 2. If Type(name) is Symbol, then if (auto const* property_key = name_arg.get_pointer(); property_key && property_key->is_symbol()) { @@ -41,15 +41,15 @@ void FunctionObject::set_function_name(Variant const& // b. If description is undefined, set name to the empty String. if (!description.has_value()) - name = ByteString::empty(); + name = ""_string; // c. Else, set name to the string-concatenation of "[", description, and "]". else - name = ByteString::formatted("[{}]", *description); + name = MUST(String::formatted("[{}]", *description)); } // 3. Else if name is a Private Name, then else if (auto const* private_name = name_arg.get_pointer()) { // a. Set name to name.[[Description]]. - name = private_name->description; + name = private_name->description.to_string(); } // NOTE: This is necessary as we use a different parameter name. else { @@ -65,7 +65,7 @@ void FunctionObject::set_function_name(Variant const& // 5. If prefix is present, then if (prefix.has_value()) { // a. Set name to the string-concatenation of prefix, the code unit 0x0020 (SPACE), and name. - name = ByteString::formatted("{} {}", *prefix, name); + name = MUST(String::formatted("{} {}", *prefix, name)); // b. If F has an [[InitialName]] internal slot, then if (is(this)) { diff --git a/Libraries/LibJS/Runtime/FunctionObject.h b/Libraries/LibJS/Runtime/FunctionObject.h index ab9c9882f60..55176f99de1 100644 --- a/Libraries/LibJS/Runtime/FunctionObject.h +++ b/Libraries/LibJS/Runtime/FunctionObject.h @@ -26,7 +26,7 @@ public: virtual ThrowCompletionOr internal_call(Value this_argument, ReadonlySpan arguments_list) = 0; virtual ThrowCompletionOr> internal_construct([[maybe_unused]] ReadonlySpan arguments_list, [[maybe_unused]] FunctionObject& new_target) { VERIFY_NOT_REACHED(); } - virtual DeprecatedFlyString const& name() const = 0; + virtual FlyString const& name() const = 0; void set_function_name(Variant const& name_arg, Optional const& prefix = {}); void set_function_length(double length); @@ -38,7 +38,7 @@ public: // [[Realm]] virtual Realm* realm() const { return nullptr; } - virtual Vector const& local_variables_names() const { VERIFY_NOT_REACHED(); } + virtual Vector const& local_variables_names() const { VERIFY_NOT_REACHED(); } virtual Vector const& formal_parameters() const { VERIFY_NOT_REACHED(); } diff --git a/Libraries/LibJS/Runtime/FunctionPrototype.h b/Libraries/LibJS/Runtime/FunctionPrototype.h index 597092965a7..e61e89fc7bd 100644 --- a/Libraries/LibJS/Runtime/FunctionPrototype.h +++ b/Libraries/LibJS/Runtime/FunctionPrototype.h @@ -19,7 +19,7 @@ public: virtual ~FunctionPrototype() override = default; virtual ThrowCompletionOr internal_call(Value this_argument, ReadonlySpan arguments_list) override; - virtual DeprecatedFlyString const& name() const override { return m_name; } + virtual FlyString const& name() const override { return m_name; } private: explicit FunctionPrototype(Realm&); @@ -31,7 +31,7 @@ private: JS_DECLARE_NATIVE_FUNCTION(symbol_has_instance); // 20.2.3: The Function prototype object has a "name" property whose value is the empty String. - DeprecatedFlyString m_name; + FlyString m_name; }; } diff --git a/Libraries/LibJS/Runtime/GlobalEnvironment.cpp b/Libraries/LibJS/Runtime/GlobalEnvironment.cpp index 35f6cc8ba65..657c040a63e 100644 --- a/Libraries/LibJS/Runtime/GlobalEnvironment.cpp +++ b/Libraries/LibJS/Runtime/GlobalEnvironment.cpp @@ -41,7 +41,7 @@ ThrowCompletionOr GlobalEnvironment::get_this_binding(VM&) const } // 9.1.1.4.1 HasBinding ( N ), https://tc39.es/ecma262/#sec-global-environment-records-hasbinding-n -ThrowCompletionOr GlobalEnvironment::has_binding(DeprecatedFlyString const& name, Optional*) const +ThrowCompletionOr GlobalEnvironment::has_binding(FlyString const& name, Optional*) const { // 1. Let DclRec be envRec.[[DeclarativeRecord]]. // 2. If ! DclRec.HasBinding(N) is true, return true. @@ -54,7 +54,7 @@ ThrowCompletionOr GlobalEnvironment::has_binding(DeprecatedFlyString const } // 9.1.1.4.2 CreateMutableBinding ( N, D ), https://tc39.es/ecma262/#sec-global-environment-records-createmutablebinding-n-d -ThrowCompletionOr GlobalEnvironment::create_mutable_binding(VM& vm, DeprecatedFlyString const& name, bool can_be_deleted) +ThrowCompletionOr GlobalEnvironment::create_mutable_binding(VM& vm, FlyString const& name, bool can_be_deleted) { // 1. Let DclRec be envRec.[[DeclarativeRecord]]. // 2. If ! DclRec.HasBinding(N) is true, throw a TypeError exception. @@ -66,7 +66,7 @@ ThrowCompletionOr GlobalEnvironment::create_mutable_binding(VM& vm, Deprec } // 9.1.1.4.3 CreateImmutableBinding ( N, S ), https://tc39.es/ecma262/#sec-global-environment-records-createimmutablebinding-n-s -ThrowCompletionOr GlobalEnvironment::create_immutable_binding(VM& vm, DeprecatedFlyString const& name, bool strict) +ThrowCompletionOr GlobalEnvironment::create_immutable_binding(VM& vm, FlyString const& name, bool strict) { // 1. Let DclRec be envRec.[[DeclarativeRecord]]. // 2. If ! DclRec.HasBinding(N) is true, throw a TypeError exception. @@ -78,7 +78,7 @@ ThrowCompletionOr GlobalEnvironment::create_immutable_binding(VM& vm, Depr } // 9.1.1.4.4 InitializeBinding ( N, V, hint ), https://tc39.es/ecma262/#sec-global-environment-records-initializebinding-n-v -ThrowCompletionOr GlobalEnvironment::initialize_binding(VM& vm, DeprecatedFlyString const& name, Value value, InitializeBindingHint hint) +ThrowCompletionOr GlobalEnvironment::initialize_binding(VM& vm, FlyString const& name, Value value, InitializeBindingHint hint) { // 1. Let DclRec be envRec.[[DeclarativeRecord]]. // 2. If ! DclRec.HasBinding(N) is true, then @@ -96,7 +96,7 @@ ThrowCompletionOr GlobalEnvironment::initialize_binding(VM& vm, Deprecated } // 9.1.1.4.5 SetMutableBinding ( N, V, S ), https://tc39.es/ecma262/#sec-global-environment-records-setmutablebinding-n-v-s -ThrowCompletionOr GlobalEnvironment::set_mutable_binding(VM& vm, DeprecatedFlyString const& name, Value value, bool strict) +ThrowCompletionOr GlobalEnvironment::set_mutable_binding(VM& vm, FlyString const& name, Value value, bool strict) { // 1. Let DclRec be envRec.[[DeclarativeRecord]]. // 2. If ! DclRec.HasBinding(N) is true, then @@ -111,7 +111,7 @@ ThrowCompletionOr GlobalEnvironment::set_mutable_binding(VM& vm, Deprecate } // 9.1.1.4.6 GetBindingValue ( N, S ), https://tc39.es/ecma262/#sec-global-environment-records-getbindingvalue-n-s -ThrowCompletionOr GlobalEnvironment::get_binding_value(VM& vm, DeprecatedFlyString const& name, bool strict) +ThrowCompletionOr GlobalEnvironment::get_binding_value(VM& vm, FlyString const& name, bool strict) { // 1. Let DclRec be envRec.[[DeclarativeRecord]]. // 2. If ! DclRec.HasBinding(N) is true, then @@ -129,7 +129,7 @@ ThrowCompletionOr GlobalEnvironment::get_binding_value(VM& vm, Deprecated } // 9.1.1.4.7 DeleteBinding ( N ), https://tc39.es/ecma262/#sec-global-environment-records-deletebinding-n -ThrowCompletionOr GlobalEnvironment::delete_binding(VM& vm, DeprecatedFlyString const& name) +ThrowCompletionOr GlobalEnvironment::delete_binding(VM& vm, FlyString const& name) { // 1. Let DclRec be envRec.[[DeclarativeRecord]]. // 2. If ! DclRec.HasBinding(N) is true, then @@ -165,7 +165,7 @@ ThrowCompletionOr GlobalEnvironment::delete_binding(VM& vm, DeprecatedFlyS } // 9.1.1.4.12 HasVarDeclaration ( N ), https://tc39.es/ecma262/#sec-hasvardeclaration -bool GlobalEnvironment::has_var_declaration(DeprecatedFlyString const& name) const +bool GlobalEnvironment::has_var_declaration(FlyString const& name) const { // 1. Let varDeclaredNames be envRec.[[VarNames]]. // 2. If varDeclaredNames contains N, return true. @@ -174,7 +174,7 @@ bool GlobalEnvironment::has_var_declaration(DeprecatedFlyString const& name) con } // 9.1.1.4.13 HasLexicalDeclaration ( N ), https://tc39.es/ecma262/#sec-haslexicaldeclaration -bool GlobalEnvironment::has_lexical_declaration(DeprecatedFlyString const& name) const +bool GlobalEnvironment::has_lexical_declaration(FlyString const& name) const { // 1. Let DclRec be envRec.[[DeclarativeRecord]]. // 2. Return ! DclRec.HasBinding(N). @@ -182,7 +182,7 @@ bool GlobalEnvironment::has_lexical_declaration(DeprecatedFlyString const& name) } // 9.1.1.4.14 HasRestrictedGlobalProperty ( N ), https://tc39.es/ecma262/#sec-hasrestrictedglobalproperty -ThrowCompletionOr GlobalEnvironment::has_restricted_global_property(DeprecatedFlyString const& name) const +ThrowCompletionOr GlobalEnvironment::has_restricted_global_property(FlyString const& name) const { // 1. Let ObjRec be envRec.[[ObjectRecord]]. // 2. Let globalObject be ObjRec.[[BindingObject]]. @@ -204,7 +204,7 @@ ThrowCompletionOr GlobalEnvironment::has_restricted_global_property(Deprec } // 9.1.1.4.15 CanDeclareGlobalVar ( N ), https://tc39.es/ecma262/#sec-candeclareglobalvar -ThrowCompletionOr GlobalEnvironment::can_declare_global_var(DeprecatedFlyString const& name) const +ThrowCompletionOr GlobalEnvironment::can_declare_global_var(FlyString const& name) const { // 1. Let ObjRec be envRec.[[ObjectRecord]]. // 2. Let globalObject be ObjRec.[[BindingObject]]. @@ -222,7 +222,7 @@ ThrowCompletionOr GlobalEnvironment::can_declare_global_var(DeprecatedFlyS } // 9.1.1.4.16 CanDeclareGlobalFunction ( N ), https://tc39.es/ecma262/#sec-candeclareglobalfunction -ThrowCompletionOr GlobalEnvironment::can_declare_global_function(DeprecatedFlyString const& name) const +ThrowCompletionOr GlobalEnvironment::can_declare_global_function(FlyString const& name) const { // 1. Let ObjRec be envRec.[[ObjectRecord]]. // 2. Let globalObject be ObjRec.[[BindingObject]]. @@ -248,7 +248,7 @@ ThrowCompletionOr GlobalEnvironment::can_declare_global_function(Deprecate } // 9.1.1.4.17 CreateGlobalVarBinding ( N, D ), https://tc39.es/ecma262/#sec-createglobalvarbinding -ThrowCompletionOr GlobalEnvironment::create_global_var_binding(DeprecatedFlyString const& name, bool can_be_deleted) +ThrowCompletionOr GlobalEnvironment::create_global_var_binding(FlyString const& name, bool can_be_deleted) { auto& vm = this->vm(); @@ -283,7 +283,7 @@ ThrowCompletionOr GlobalEnvironment::create_global_var_binding(DeprecatedF } // 9.1.1.4.18 CreateGlobalFunctionBinding ( N, V, D ), https://tc39.es/ecma262/#sec-createglobalfunctionbinding -ThrowCompletionOr GlobalEnvironment::create_global_function_binding(DeprecatedFlyString const& name, Value value, bool can_be_deleted) +ThrowCompletionOr GlobalEnvironment::create_global_function_binding(FlyString const& name, Value value, bool can_be_deleted) { // 1. Let ObjRec be envRec.[[ObjectRecord]]. // 2. Let globalObject be ObjRec.[[BindingObject]]. diff --git a/Libraries/LibJS/Runtime/GlobalEnvironment.h b/Libraries/LibJS/Runtime/GlobalEnvironment.h index b23fef7bb16..90d8a971758 100644 --- a/Libraries/LibJS/Runtime/GlobalEnvironment.h +++ b/Libraries/LibJS/Runtime/GlobalEnvironment.h @@ -18,25 +18,25 @@ public: virtual bool has_this_binding() const final { return true; } virtual ThrowCompletionOr get_this_binding(VM&) const final; - virtual ThrowCompletionOr has_binding(DeprecatedFlyString const& name, Optional* = nullptr) const override; - virtual ThrowCompletionOr create_mutable_binding(VM&, DeprecatedFlyString const& name, bool can_be_deleted) override; - virtual ThrowCompletionOr create_immutable_binding(VM&, DeprecatedFlyString const& name, bool strict) override; - virtual ThrowCompletionOr initialize_binding(VM&, DeprecatedFlyString const& name, Value, Environment::InitializeBindingHint) override; - virtual ThrowCompletionOr set_mutable_binding(VM&, DeprecatedFlyString const& name, Value, bool strict) override; - virtual ThrowCompletionOr get_binding_value(VM&, DeprecatedFlyString const& name, bool strict) override; - virtual ThrowCompletionOr delete_binding(VM&, DeprecatedFlyString const& name) override; + virtual ThrowCompletionOr has_binding(FlyString const& name, Optional* = nullptr) const override; + virtual ThrowCompletionOr create_mutable_binding(VM&, FlyString const& name, bool can_be_deleted) override; + virtual ThrowCompletionOr create_immutable_binding(VM&, FlyString const& name, bool strict) override; + virtual ThrowCompletionOr initialize_binding(VM&, FlyString const& name, Value, Environment::InitializeBindingHint) override; + virtual ThrowCompletionOr set_mutable_binding(VM&, FlyString const& name, Value, bool strict) override; + virtual ThrowCompletionOr get_binding_value(VM&, FlyString const& name, bool strict) override; + virtual ThrowCompletionOr delete_binding(VM&, FlyString const& name) override; ObjectEnvironment& object_record() { return *m_object_record; } Object& global_this_value() { return *m_global_this_value; } DeclarativeEnvironment& declarative_record() { return *m_declarative_record; } - bool has_var_declaration(DeprecatedFlyString const& name) const; - bool has_lexical_declaration(DeprecatedFlyString const& name) const; - ThrowCompletionOr has_restricted_global_property(DeprecatedFlyString const& name) const; - ThrowCompletionOr can_declare_global_var(DeprecatedFlyString const& name) const; - ThrowCompletionOr can_declare_global_function(DeprecatedFlyString const& name) const; - ThrowCompletionOr create_global_var_binding(DeprecatedFlyString const& name, bool can_be_deleted); - ThrowCompletionOr create_global_function_binding(DeprecatedFlyString const& name, Value, bool can_be_deleted); + bool has_var_declaration(FlyString const& name) const; + bool has_lexical_declaration(FlyString const& name) const; + ThrowCompletionOr has_restricted_global_property(FlyString const& name) const; + ThrowCompletionOr can_declare_global_var(FlyString const& name) const; + ThrowCompletionOr can_declare_global_function(FlyString const& name) const; + ThrowCompletionOr create_global_var_binding(FlyString const& name, bool can_be_deleted); + ThrowCompletionOr create_global_function_binding(FlyString const& name, Value, bool can_be_deleted); private: GlobalEnvironment(Object&, Object& this_value); @@ -47,7 +47,7 @@ private: GC::Ptr m_object_record; // [[ObjectRecord]] GC::Ptr m_global_this_value; // [[GlobalThisValue]] GC::Ptr m_declarative_record; // [[DeclarativeRecord]] - Vector m_var_names; // [[VarNames]] + Vector m_var_names; // [[VarNames]] }; template<> diff --git a/Libraries/LibJS/Runtime/JSONObject.cpp b/Libraries/LibJS/Runtime/JSONObject.cpp index c8c343c958b..1286d2452bb 100644 --- a/Libraries/LibJS/Runtime/JSONObject.cpp +++ b/Libraries/LibJS/Runtime/JSONObject.cpp @@ -239,7 +239,7 @@ ThrowCompletionOr JSONObject::serialize_json_object(VM& vm, StringifySta if (serialized_property_string.has_value()) { property_strings.append(MUST(String::formatted( "{}:{}{}", - quote_json_string(MUST(String::from_byte_string(key.to_string()))), + quote_json_string(key.to_string()), state.gap.is_empty() ? "" : " ", serialized_property_string))); } diff --git a/Libraries/LibJS/Runtime/ModuleEnvironment.cpp b/Libraries/LibJS/Runtime/ModuleEnvironment.cpp index a3e69ff51c4..2f552be1b71 100644 --- a/Libraries/LibJS/Runtime/ModuleEnvironment.cpp +++ b/Libraries/LibJS/Runtime/ModuleEnvironment.cpp @@ -20,7 +20,7 @@ ModuleEnvironment::ModuleEnvironment(Environment* outer_environment) } // 9.1.1.5.1 GetBindingValue ( N, S ), https://tc39.es/ecma262/#sec-module-environment-records-getbindingvalue-n-s -ThrowCompletionOr ModuleEnvironment::get_binding_value(VM& vm, DeprecatedFlyString const& name, bool strict) +ThrowCompletionOr ModuleEnvironment::get_binding_value(VM& vm, FlyString const& name, bool strict) { // 1. Assert: S is true. VERIFY(strict); @@ -51,7 +51,7 @@ ThrowCompletionOr ModuleEnvironment::get_binding_value(VM& vm, Deprecated } // 9.1.1.5.2 DeleteBinding ( N ), https://tc39.es/ecma262/#sec-module-environment-records-deletebinding-n -ThrowCompletionOr ModuleEnvironment::delete_binding(VM&, DeprecatedFlyString const&) +ThrowCompletionOr ModuleEnvironment::delete_binding(VM&, FlyString const&) { // The DeleteBinding concrete method of a module Environment Record is never used within this specification. VERIFY_NOT_REACHED(); @@ -65,7 +65,7 @@ ThrowCompletionOr ModuleEnvironment::get_this_binding(VM&) const } // 9.1.1.5.5 CreateImportBinding ( N, M, N2 ), https://tc39.es/ecma262/#sec-createimportbinding -ThrowCompletionOr ModuleEnvironment::create_import_binding(DeprecatedFlyString name, Module* module, DeprecatedFlyString binding_name) +ThrowCompletionOr ModuleEnvironment::create_import_binding(FlyString name, Module* module, FlyString binding_name) { // 1. Assert: envRec does not already have a binding for N. VERIFY(!get_indirect_binding(name)); @@ -82,7 +82,7 @@ ThrowCompletionOr ModuleEnvironment::create_import_binding(DeprecatedFlySt return {}; } -ModuleEnvironment::IndirectBinding const* ModuleEnvironment::get_indirect_binding(DeprecatedFlyString const& name) const +ModuleEnvironment::IndirectBinding const* ModuleEnvironment::get_indirect_binding(FlyString const& name) const { auto binding_or_end = m_indirect_bindings.find_if([&](IndirectBinding const& binding) { return binding.name == name; @@ -93,7 +93,7 @@ ModuleEnvironment::IndirectBinding const* ModuleEnvironment::get_indirect_bindin return &(*binding_or_end); } -Optional ModuleEnvironment::find_binding_and_index(DeprecatedFlyString const& name) const +Optional ModuleEnvironment::find_binding_and_index(FlyString const& name) const { auto* indirect_binding = get_indirect_binding(name); if (indirect_binding != nullptr) { diff --git a/Libraries/LibJS/Runtime/ModuleEnvironment.h b/Libraries/LibJS/Runtime/ModuleEnvironment.h index 35de87de90c..daec2c0ca1d 100644 --- a/Libraries/LibJS/Runtime/ModuleEnvironment.h +++ b/Libraries/LibJS/Runtime/ModuleEnvironment.h @@ -22,11 +22,11 @@ public: // in Table 18 and share the same specifications for all of those methods except for // GetBindingValue, DeleteBinding, HasThisBinding and GetThisBinding. // In addition, module Environment Records support the methods listed in Table 24. - virtual ThrowCompletionOr get_binding_value(VM&, DeprecatedFlyString const& name, bool strict) override; - virtual ThrowCompletionOr delete_binding(VM&, DeprecatedFlyString const& name) override; + virtual ThrowCompletionOr get_binding_value(VM&, FlyString const& name, bool strict) override; + virtual ThrowCompletionOr delete_binding(VM&, FlyString const& name) override; virtual bool has_this_binding() const final { return true; } virtual ThrowCompletionOr get_this_binding(VM&) const final; - ThrowCompletionOr create_import_binding(DeprecatedFlyString name, Module* module, DeprecatedFlyString binding_name); + ThrowCompletionOr create_import_binding(FlyString name, Module* module, FlyString binding_name); private: explicit ModuleEnvironment(Environment* outer_environment); @@ -34,13 +34,13 @@ private: virtual void visit_edges(Visitor&) override; struct IndirectBinding { - DeprecatedFlyString name; + FlyString name; GC::Ptr module; - DeprecatedFlyString binding_name; + FlyString binding_name; }; - IndirectBinding const* get_indirect_binding(DeprecatedFlyString const& name) const; + IndirectBinding const* get_indirect_binding(FlyString const& name) const; - virtual Optional find_binding_and_index(DeprecatedFlyString const& name) const override; + virtual Optional find_binding_and_index(FlyString const& name) const override; // FIXME: Since we always access this via the name this could be a map. Vector m_indirect_bindings; diff --git a/Libraries/LibJS/Runtime/ModuleNamespaceObject.cpp b/Libraries/LibJS/Runtime/ModuleNamespaceObject.cpp index 3aec92d5741..055d6b56ecd 100644 --- a/Libraries/LibJS/Runtime/ModuleNamespaceObject.cpp +++ b/Libraries/LibJS/Runtime/ModuleNamespaceObject.cpp @@ -13,15 +13,15 @@ namespace JS { GC_DEFINE_ALLOCATOR(ModuleNamespaceObject); -ModuleNamespaceObject::ModuleNamespaceObject(Realm& realm, Module* module, Vector exports) +ModuleNamespaceObject::ModuleNamespaceObject(Realm& realm, Module* module, Vector exports) : Object(ConstructWithPrototypeTag::Tag, realm.intrinsics().object_prototype(), MayInterfereWithIndexedPropertyAccess::Yes) , m_module(module) , m_exports(move(exports)) { // Note: We just perform step 6 of 10.4.6.12 ModuleNamespaceCreate ( module, exports ), https://tc39.es/ecma262/#sec-modulenamespacecreate // 6. Let sortedExports be a List whose elements are the elements of exports ordered as if an Array of the same values had been sorted using %Array.prototype.sort% using undefined as comparefn. - quick_sort(m_exports, [&](DeprecatedFlyString const& lhs, DeprecatedFlyString const& rhs) { - return lhs.view() < rhs.view(); + quick_sort(m_exports, [&](FlyString const& lhs, FlyString const& rhs) { + return lhs.bytes_as_string_view() < rhs.bytes_as_string_view(); }); } diff --git a/Libraries/LibJS/Runtime/ModuleNamespaceObject.h b/Libraries/LibJS/Runtime/ModuleNamespaceObject.h index 96faec68046..388e7a07071 100644 --- a/Libraries/LibJS/Runtime/ModuleNamespaceObject.h +++ b/Libraries/LibJS/Runtime/ModuleNamespaceObject.h @@ -33,12 +33,12 @@ public: virtual void initialize(Realm&) override; private: - ModuleNamespaceObject(Realm&, Module* module, Vector exports); + ModuleNamespaceObject(Realm&, Module* module, Vector exports); virtual void visit_edges(Visitor&) override; - GC::Ptr m_module; // [[Module]] - Vector m_exports; // [[Exports]] + GC::Ptr m_module; // [[Module]] + Vector m_exports; // [[Exports]] }; } diff --git a/Libraries/LibJS/Runtime/ModuleRequest.h b/Libraries/LibJS/Runtime/ModuleRequest.h index 34f84d8baae..ab44b51b5bf 100644 --- a/Libraries/LibJS/Runtime/ModuleRequest.h +++ b/Libraries/LibJS/Runtime/ModuleRequest.h @@ -7,21 +7,21 @@ #pragma once -#include +#include #include #include namespace JS { struct ModuleWithSpecifier { - ByteString specifier; // [[Specifier]] + String specifier; // [[Specifier]] GC::Ref module; // [[Module]] }; // https://tc39.es/proposal-import-attributes/#importattribute-record struct ImportAttribute { - ByteString key; - ByteString value; + String key; + String value; bool operator==(ImportAttribute const&) const = default; }; @@ -30,20 +30,20 @@ struct ImportAttribute { struct ModuleRequest { ModuleRequest() = default; - explicit ModuleRequest(DeprecatedFlyString specifier) + explicit ModuleRequest(FlyString specifier) : module_specifier(move(specifier)) { } - ModuleRequest(DeprecatedFlyString specifier, Vector attributes); + ModuleRequest(FlyString specifier, Vector attributes); - void add_attribute(ByteString key, ByteString value) + void add_attribute(String key, String value) { attributes.empend(move(key), move(value)); } - DeprecatedFlyString module_specifier; // [[Specifier]] - Vector attributes; // [[Attributes]] + FlyString module_specifier; // [[Specifier]] + Vector attributes; // [[Attributes]] bool operator==(ModuleRequest const&) const = default; }; diff --git a/Libraries/LibJS/Runtime/NativeFunction.cpp b/Libraries/LibJS/Runtime/NativeFunction.cpp index 7f8ef8ba6b0..37a44d42902 100644 --- a/Libraries/LibJS/Runtime/NativeFunction.cpp +++ b/Libraries/LibJS/Runtime/NativeFunction.cpp @@ -68,7 +68,7 @@ GC::Ref NativeFunction::create(Realm& allocating_realm, Function return function; } -GC::Ref NativeFunction::create(Realm& realm, DeprecatedFlyString const& name, Function(VM&)> function) +GC::Ref NativeFunction::create(Realm& realm, FlyString const& name, Function(VM&)> function) { return realm.create(name, GC::create_function(realm.heap(), move(function)), realm.intrinsics().function_prototype()); } @@ -90,7 +90,7 @@ NativeFunction::NativeFunction(Object& prototype) { } -NativeFunction::NativeFunction(DeprecatedFlyString name, GC::Ptr(VM&)>> native_function, Object& prototype) +NativeFunction::NativeFunction(FlyString name, GC::Ptr(VM&)>> native_function, Object& prototype) : FunctionObject(prototype) , m_name(move(name)) , m_native_function(move(native_function)) @@ -98,7 +98,7 @@ NativeFunction::NativeFunction(DeprecatedFlyString name, GC::Ptr create(Realm&, ESCAPING Function(VM&)> behaviour, i32 length, PropertyKey const& name = FlyString {}, Optional = {}, Optional prototype = {}, Optional const& prefix = {}); - static GC::Ref create(Realm&, DeprecatedFlyString const& name, ESCAPING Function(VM&)>); + static GC::Ref create(Realm&, FlyString const& name, ESCAPING Function(VM&)>); virtual ~NativeFunction() override = default; @@ -34,18 +34,18 @@ public: virtual ThrowCompletionOr call(); virtual ThrowCompletionOr> construct(FunctionObject& new_target); - virtual DeprecatedFlyString const& name() const override { return m_name; } + virtual FlyString const& name() const override { return m_name; } virtual bool is_strict_mode() const override; virtual bool has_constructor() const override { return false; } virtual Realm* realm() const override { return m_realm; } - Optional const& initial_name() const { return m_initial_name; } - void set_initial_name(Badge, DeprecatedFlyString initial_name) { m_initial_name = move(initial_name); } + Optional const& initial_name() const { return m_initial_name; } + void set_initial_name(Badge, FlyString initial_name) { m_initial_name = move(initial_name); } protected: - NativeFunction(DeprecatedFlyString name, Object& prototype); + NativeFunction(FlyString name, Object& prototype); NativeFunction(GC::Ptr(VM&)>>, Object* prototype, Realm& realm); - NativeFunction(DeprecatedFlyString name, GC::Ptr(VM&)>>, Object& prototype); + NativeFunction(FlyString name, GC::Ptr(VM&)>>, Object& prototype); explicit NativeFunction(Object& prototype); virtual void initialize(Realm&) override; @@ -54,9 +54,9 @@ protected: private: virtual bool is_native_function() const final { return true; } - DeprecatedFlyString m_name; + FlyString m_name; GC::Ptr m_name_string; - Optional m_initial_name; // [[InitialName]] + Optional m_initial_name; // [[InitialName]] GC::Ptr(VM&)>> m_native_function; GC::Ptr m_realm; }; diff --git a/Libraries/LibJS/Runtime/Object.cpp b/Libraries/LibJS/Runtime/Object.cpp index b761873aeda..7f0bd7b5511 100644 --- a/Libraries/LibJS/Runtime/Object.cpp +++ b/Libraries/LibJS/Runtime/Object.cpp @@ -25,7 +25,7 @@ namespace JS { GC_DEFINE_ALLOCATOR(Object); -static HashMap, HashMap> s_intrinsics; +static HashMap, HashMap> s_intrinsics; // 10.1.12 OrdinaryObjectCreate ( proto [ , additionalInternalSlotsList ] ), https://tc39.es/ecma262/#sec-ordinaryobjectcreate GC::Ref Object::create(Realm& realm, Object* prototype) @@ -1369,7 +1369,7 @@ Optional Object::enumerate_object_properties(Function visited; + HashTable visited; auto const* target = this; while (target) { @@ -1377,7 +1377,7 @@ Optional Object::enumerate_object_properties(Functioninternal_get_own_property(property_key)); diff --git a/Libraries/LibJS/Runtime/ObjectEnvironment.cpp b/Libraries/LibJS/Runtime/ObjectEnvironment.cpp index da5571ff22a..41b1b3a731a 100644 --- a/Libraries/LibJS/Runtime/ObjectEnvironment.cpp +++ b/Libraries/LibJS/Runtime/ObjectEnvironment.cpp @@ -27,7 +27,7 @@ void ObjectEnvironment::visit_edges(Cell::Visitor& visitor) } // 9.1.1.2.1 HasBinding ( N ), https://tc39.es/ecma262/#sec-object-environment-records-hasbinding-n -ThrowCompletionOr ObjectEnvironment::has_binding(DeprecatedFlyString const& name, Optional*) const +ThrowCompletionOr ObjectEnvironment::has_binding(FlyString const& name, Optional*) const { auto& vm = this->vm(); @@ -62,7 +62,7 @@ ThrowCompletionOr ObjectEnvironment::has_binding(DeprecatedFlyString const } // 9.1.1.2.2 CreateMutableBinding ( N, D ), https://tc39.es/ecma262/#sec-object-environment-records-createmutablebinding-n-d -ThrowCompletionOr ObjectEnvironment::create_mutable_binding(VM&, DeprecatedFlyString const& name, bool can_be_deleted) +ThrowCompletionOr ObjectEnvironment::create_mutable_binding(VM&, FlyString const& name, bool can_be_deleted) { // 1. Let bindingObject be envRec.[[BindingObject]]. // 2. Perform ? DefinePropertyOrThrow(bindingObject, N, PropertyDescriptor { [[Value]]: undefined, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: D }). @@ -73,14 +73,14 @@ ThrowCompletionOr ObjectEnvironment::create_mutable_binding(VM&, Deprecate } // 9.1.1.2.3 CreateImmutableBinding ( N, S ), https://tc39.es/ecma262/#sec-object-environment-records-createimmutablebinding-n-s -ThrowCompletionOr ObjectEnvironment::create_immutable_binding(VM&, DeprecatedFlyString const&, bool) +ThrowCompletionOr ObjectEnvironment::create_immutable_binding(VM&, FlyString const&, bool) { // "The CreateImmutableBinding concrete method of an object Environment Record is never used within this specification." VERIFY_NOT_REACHED(); } // 9.1.1.2.4 InitializeBinding ( N, V ), https://tc39.es/ecma262/#sec-object-environment-records-initializebinding-n-v -ThrowCompletionOr ObjectEnvironment::initialize_binding(VM& vm, DeprecatedFlyString const& name, Value value, Environment::InitializeBindingHint hint) +ThrowCompletionOr ObjectEnvironment::initialize_binding(VM& vm, FlyString const& name, Value value, Environment::InitializeBindingHint hint) { // 1. Assert: hint is normal. VERIFY(hint == Environment::InitializeBindingHint::Normal); @@ -93,7 +93,7 @@ ThrowCompletionOr ObjectEnvironment::initialize_binding(VM& vm, Deprecated } // 9.1.1.2.5 SetMutableBinding ( N, V, S ), https://tc39.es/ecma262/#sec-object-environment-records-setmutablebinding-n-v-s -ThrowCompletionOr ObjectEnvironment::set_mutable_binding(VM&, DeprecatedFlyString const& name, Value value, bool strict) +ThrowCompletionOr ObjectEnvironment::set_mutable_binding(VM&, FlyString const& name, Value value, bool strict) { auto& vm = this->vm(); @@ -135,7 +135,7 @@ ThrowCompletionOr ObjectEnvironment::set_mutable_binding(VM&, DeprecatedFl } // 9.1.1.2.6 GetBindingValue ( N, S ), https://tc39.es/ecma262/#sec-object-environment-records-getbindingvalue-n-s -ThrowCompletionOr ObjectEnvironment::get_binding_value(VM&, DeprecatedFlyString const& name, bool strict) +ThrowCompletionOr ObjectEnvironment::get_binding_value(VM&, FlyString const& name, bool strict) { auto& vm = this->vm(); @@ -164,7 +164,7 @@ ThrowCompletionOr ObjectEnvironment::get_binding_value(VM&, DeprecatedFly } // 9.1.1.2.7 DeleteBinding ( N ), https://tc39.es/ecma262/#sec-object-environment-records-deletebinding-n -ThrowCompletionOr ObjectEnvironment::delete_binding(VM&, DeprecatedFlyString const& name) +ThrowCompletionOr ObjectEnvironment::delete_binding(VM&, FlyString const& name) { // 1. Let bindingObject be envRec.[[BindingObject]]. // 2. Return ? bindingObject.[[Delete]](N). diff --git a/Libraries/LibJS/Runtime/ObjectEnvironment.h b/Libraries/LibJS/Runtime/ObjectEnvironment.h index b739f060d63..509f6675ab5 100644 --- a/Libraries/LibJS/Runtime/ObjectEnvironment.h +++ b/Libraries/LibJS/Runtime/ObjectEnvironment.h @@ -20,13 +20,13 @@ public: Yes, }; - virtual ThrowCompletionOr has_binding(DeprecatedFlyString const& name, Optional* = nullptr) const override; - virtual ThrowCompletionOr create_mutable_binding(VM&, DeprecatedFlyString const& name, bool can_be_deleted) override; - virtual ThrowCompletionOr create_immutable_binding(VM&, DeprecatedFlyString const& name, bool strict) override; - virtual ThrowCompletionOr initialize_binding(VM&, DeprecatedFlyString const& name, Value, Environment::InitializeBindingHint) override; - virtual ThrowCompletionOr set_mutable_binding(VM&, DeprecatedFlyString const& name, Value, bool strict) override; - virtual ThrowCompletionOr get_binding_value(VM&, DeprecatedFlyString const& name, bool strict) override; - virtual ThrowCompletionOr delete_binding(VM&, DeprecatedFlyString const& name) override; + virtual ThrowCompletionOr has_binding(FlyString const& name, Optional* = nullptr) const override; + virtual ThrowCompletionOr create_mutable_binding(VM&, FlyString const& name, bool can_be_deleted) override; + virtual ThrowCompletionOr create_immutable_binding(VM&, FlyString const& name, bool strict) override; + virtual ThrowCompletionOr initialize_binding(VM&, FlyString const& name, Value, Environment::InitializeBindingHint) override; + virtual ThrowCompletionOr set_mutable_binding(VM&, FlyString const& name, Value, bool strict) override; + virtual ThrowCompletionOr get_binding_value(VM&, FlyString const& name, bool strict) override; + virtual ThrowCompletionOr delete_binding(VM&, FlyString const& name) override; // 9.1.1.2.10 WithBaseObject ( ), https://tc39.es/ecma262/#sec-object-environment-records-withbaseobject virtual Object* with_base_object() const override diff --git a/Libraries/LibJS/Runtime/PrivateEnvironment.cpp b/Libraries/LibJS/Runtime/PrivateEnvironment.cpp index b0824720515..45c5ab1ca73 100644 --- a/Libraries/LibJS/Runtime/PrivateEnvironment.cpp +++ b/Libraries/LibJS/Runtime/PrivateEnvironment.cpp @@ -21,7 +21,7 @@ PrivateEnvironment::PrivateEnvironment(PrivateEnvironment* parent) // Note: we start at one such that 0 can be invalid / default initialized. u64 PrivateEnvironment::s_next_id = 1u; -PrivateName PrivateEnvironment::resolve_private_identifier(DeprecatedFlyString const& identifier) const +PrivateName PrivateEnvironment::resolve_private_identifier(FlyString const& identifier) const { auto name_or_end = find_private_name(identifier); @@ -34,7 +34,7 @@ PrivateName PrivateEnvironment::resolve_private_identifier(DeprecatedFlyString c return m_outer_environment->resolve_private_identifier(identifier); } -void PrivateEnvironment::add_private_name(DeprecatedFlyString description) +void PrivateEnvironment::add_private_name(FlyString description) { if (!find_private_name(description).is_end()) return; diff --git a/Libraries/LibJS/Runtime/PrivateEnvironment.h b/Libraries/LibJS/Runtime/PrivateEnvironment.h index 4bc3a7dd616..d79d6386cde 100644 --- a/Libraries/LibJS/Runtime/PrivateEnvironment.h +++ b/Libraries/LibJS/Runtime/PrivateEnvironment.h @@ -6,7 +6,7 @@ #pragma once -#include +#include #include #include #include @@ -16,14 +16,14 @@ namespace JS { struct PrivateName { PrivateName() = default; - PrivateName(u64 unique_id, DeprecatedFlyString description) + PrivateName(u64 unique_id, FlyString description) : unique_id(unique_id) , description(move(description)) { } u64 unique_id { 0 }; - DeprecatedFlyString description; + FlyString description; bool operator==(PrivateName const& rhs) const; }; @@ -33,9 +33,9 @@ class PrivateEnvironment : public Cell { GC_DECLARE_ALLOCATOR(PrivateEnvironment); public: - PrivateName resolve_private_identifier(DeprecatedFlyString const& identifier) const; + PrivateName resolve_private_identifier(FlyString const& identifier) const; - void add_private_name(DeprecatedFlyString description); + void add_private_name(FlyString description); PrivateEnvironment* outer_environment() { return m_outer_environment; } PrivateEnvironment const* outer_environment() const { return m_outer_environment; } @@ -45,7 +45,7 @@ private: virtual void visit_edges(Visitor&) override; - auto find_private_name(DeprecatedFlyString const& description) const + auto find_private_name(FlyString const& description) const { return m_private_names.find_if([&](PrivateName const& private_name) { return private_name.description == description; diff --git a/Libraries/LibJS/Runtime/PropertyKey.h b/Libraries/LibJS/Runtime/PropertyKey.h index ec363f116f9..950644bb6b9 100644 --- a/Libraries/LibJS/Runtime/PropertyKey.h +++ b/Libraries/LibJS/Runtime/PropertyKey.h @@ -6,7 +6,6 @@ #pragma once -#include #include #include #include @@ -31,7 +30,7 @@ public: return PropertyKey { value.as_symbol() }; if (value.is_integral_number() && value.as_double() >= 0 && value.as_double() < NumericLimits::max()) return static_cast(value.as_double()); - return TRY(value.to_byte_string(vm)); + return TRY(value.to_string(vm)); } PropertyKey() = delete; @@ -45,24 +44,19 @@ public: VERIFY(index >= 0); if constexpr (NumericLimits::max() >= NumericLimits::max()) { if (index >= NumericLimits::max()) { - m_data = DeprecatedFlyString { ByteString::number(index) }; + m_data = FlyString { String::number(index) }; return; } } } - PropertyKey(DeprecatedFlyString string, StringMayBeNumber string_may_be_number = StringMayBeNumber::Yes) + PropertyKey(FlyString string, StringMayBeNumber string_may_be_number = StringMayBeNumber::Yes) : m_data { try_coerce_into_number(move(string), string_may_be_number) } { } PropertyKey(String const& string) - : PropertyKey(DeprecatedFlyString(string.to_byte_string())) - { - } - - PropertyKey(FlyString const& string) - : PropertyKey(string.to_deprecated_fly_string()) + : PropertyKey(FlyString(string)) { } @@ -74,26 +68,26 @@ public: PropertyKey(StringOrSymbol const& string_or_symbol) : m_data { string_or_symbol.is_string() - ? Variant, u32> { string_or_symbol.as_string() } - : Variant, u32> { const_cast(string_or_symbol.as_symbol()) } + ? Variant, u32> { string_or_symbol.as_string() } + : Variant, u32> { const_cast(string_or_symbol.as_symbol()) } } { } bool is_number() const { return m_data.has(); } - bool is_string() const { return m_data.has(); } + bool is_string() const { return m_data.has(); } bool is_symbol() const { return m_data.has>(); } u32 as_number() const { return m_data.get(); } - DeprecatedFlyString const& as_string() const { return m_data.get(); } + FlyString const& as_string() const { return m_data.get(); } Symbol const* as_symbol() const { return m_data.get>(); } - ByteString to_string() const + String to_string() const { VERIFY(!is_symbol()); if (is_string()) - return as_string(); - return ByteString::number(as_number()); + return as_string().to_string(); + return String::number(as_number()); } StringOrSymbol to_string_or_symbol() const @@ -109,21 +103,21 @@ public: private: friend Traits; - static Variant try_coerce_into_number(DeprecatedFlyString string, StringMayBeNumber string_may_be_number) + static Variant try_coerce_into_number(FlyString string, StringMayBeNumber string_may_be_number) { if (string_may_be_number != StringMayBeNumber::Yes) return string; if (string.is_empty()) return string; - if (string.starts_with("0"sv) && string.length() != 1) + if (string.bytes_as_string_view().starts_with("0"sv) && string.bytes().size() != 1) return string; - auto property_index = string.to_number(TrimWhitespace::No); + auto property_index = string.bytes_as_string_view().to_number(TrimWhitespace::No); if (!property_index.has_value() || property_index.value() >= NumericLimits::max()) return string; return property_index.release_value(); } - Variant> m_data; + Variant> m_data; }; } @@ -135,7 +129,7 @@ struct Traits : public DefaultTraits { static unsigned hash(JS::PropertyKey const& name) { return name.m_data.visit( - [](DeprecatedFlyString const& string) { return string.hash(); }, + [](FlyString const& string) { return string.hash(); }, [](GC::Root const& symbol) { return ptr_hash(symbol.ptr()); }, [](u32 const& number) { return int_hash(number); }); } diff --git a/Libraries/LibJS/Runtime/ProxyObject.cpp b/Libraries/LibJS/Runtime/ProxyObject.cpp index 39abfc399ce..ec29e9fd84f 100644 --- a/Libraries/LibJS/Runtime/ProxyObject.cpp +++ b/Libraries/LibJS/Runtime/ProxyObject.cpp @@ -899,7 +899,7 @@ void ProxyObject::visit_edges(Cell::Visitor& visitor) visitor.visit(m_handler); } -DeprecatedFlyString const& ProxyObject::name() const +FlyString const& ProxyObject::name() const { VERIFY(is_function()); return static_cast(*m_target).name(); diff --git a/Libraries/LibJS/Runtime/ProxyObject.h b/Libraries/LibJS/Runtime/ProxyObject.h index 6ba319d4900..e1cf4e73d0b 100644 --- a/Libraries/LibJS/Runtime/ProxyObject.h +++ b/Libraries/LibJS/Runtime/ProxyObject.h @@ -21,7 +21,7 @@ public: virtual ~ProxyObject() override = default; - virtual DeprecatedFlyString const& name() const override; + virtual FlyString const& name() const override; virtual bool has_constructor() const override; Object const& target() const { return m_target; } diff --git a/Libraries/LibJS/Runtime/Reference.cpp b/Libraries/LibJS/Runtime/Reference.cpp index f6b3de56563..e9e0ff38d6a 100644 --- a/Libraries/LibJS/Runtime/Reference.cpp +++ b/Libraries/LibJS/Runtime/Reference.cpp @@ -208,7 +208,7 @@ ThrowCompletionOr Reference::initialize_referenced_binding(VM& vm, Value v } // 6.2.4.9 MakePrivateReference ( baseValue, privateIdentifier ), https://tc39.es/ecma262/#sec-makeprivatereference -Reference make_private_reference(VM& vm, Value base_value, DeprecatedFlyString const& private_identifier) +Reference make_private_reference(VM& vm, Value base_value, FlyString const& private_identifier) { // 1. Let privEnv be the running execution context's PrivateEnvironment. auto private_environment = vm.running_execution_context().private_environment; diff --git a/Libraries/LibJS/Runtime/Reference.h b/Libraries/LibJS/Runtime/Reference.h index 5c1ec28846d..f9f68204175 100644 --- a/Libraries/LibJS/Runtime/Reference.h +++ b/Libraries/LibJS/Runtime/Reference.h @@ -13,7 +13,7 @@ namespace JS { -Reference make_private_reference(VM&, Value base_value, DeprecatedFlyString const& private_identifier); +Reference make_private_reference(VM&, Value base_value, FlyString const& private_identifier); class Reference { public: @@ -39,7 +39,7 @@ public: { } - Reference(Environment& base, DeprecatedFlyString referenced_name, bool strict = false, Optional environment_coordinate = {}) + Reference(Environment& base, FlyString referenced_name, bool strict = false, Optional environment_coordinate = {}) : m_base_type(BaseType::Environment) , m_base_environment(&base) , m_name(move(referenced_name)) diff --git a/Libraries/LibJS/Runtime/RegExpObject.cpp b/Libraries/LibJS/Runtime/RegExpObject.cpp index 972f343c788..59f331f1965 100644 --- a/Libraries/LibJS/Runtime/RegExpObject.cpp +++ b/Libraries/LibJS/Runtime/RegExpObject.cpp @@ -19,7 +19,7 @@ namespace JS { GC_DEFINE_ALLOCATOR(RegExpObject); -Result, ByteString> regex_flags_from_string(StringView flags) +Result, String> regex_flags_from_string(StringView flags) { bool d = false, g = false, i = false, m = false, s = false, u = false, y = false, v = false; auto options = RegExpObject::default_flags; @@ -28,42 +28,42 @@ Result, ByteString> regex_flags_from_string switch (ch) { case 'd': if (d) - return ByteString::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch); + return MUST(String::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch)); d = true; break; case 'g': if (g) - return ByteString::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch); + return MUST(String::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch)); g = true; options |= regex::ECMAScriptFlags::Global; break; case 'i': if (i) - return ByteString::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch); + return MUST(String::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch)); i = true; options |= regex::ECMAScriptFlags::Insensitive; break; case 'm': if (m) - return ByteString::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch); + return MUST(String::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch)); m = true; options |= regex::ECMAScriptFlags::Multiline; break; case 's': if (s) - return ByteString::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch); + return MUST(String::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch)); s = true; options |= regex::ECMAScriptFlags::SingleLine; break; case 'u': if (u) - return ByteString::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch); + return MUST(String::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch)); u = true; options |= regex::ECMAScriptFlags::Unicode; break; case 'y': if (y) - return ByteString::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch); + return MUST(String::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch)); y = true; // Now for the more interesting flag, 'sticky' actually unsets 'global', part of which is the default. options.reset_flag(regex::ECMAScriptFlags::Global); @@ -75,12 +75,12 @@ Result, ByteString> regex_flags_from_string break; case 'v': if (v) - return ByteString::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch); + return MUST(String::formatted(ErrorType::RegExpObjectRepeatedFlag.message(), ch)); v = true; options |= regex::ECMAScriptFlags::UnicodeSets; break; default: - return ByteString::formatted(ErrorType::RegExpObjectBadFlag.message(), ch); + return MUST(String::formatted(ErrorType::RegExpObjectBadFlag.message(), ch)); } } @@ -88,14 +88,14 @@ Result, ByteString> regex_flags_from_string } // 22.2.3.4 Static Semantics: ParsePattern ( patternText, u, v ), https://tc39.es/ecma262/#sec-parsepattern -ErrorOr parse_regex_pattern(StringView pattern, bool unicode, bool unicode_sets) +ErrorOr parse_regex_pattern(StringView pattern, bool unicode, bool unicode_sets) { if (unicode && unicode_sets) - return ParseRegexPatternError { ByteString::formatted(ErrorType::RegExpObjectIncompatibleFlags.message(), 'u', 'v') }; + return ParseRegexPatternError { MUST(String::formatted(ErrorType::RegExpObjectIncompatibleFlags.message(), 'u', 'v')) }; auto utf16_pattern_result = AK::utf8_to_utf16(pattern); if (utf16_pattern_result.is_error()) - return ParseRegexPatternError { "Out of memory"sv }; + return ParseRegexPatternError { "Out of memory"_string }; auto utf16_pattern = utf16_pattern_result.release_value(); Utf16View utf16_pattern_view { utf16_pattern }; @@ -133,11 +133,11 @@ ErrorOr parse_regex_pattern(StringView patte previous_code_unit_was_backslash = false; } - return builder.to_byte_string(); + return builder.to_string_without_validation(); } // 22.2.3.4 Static Semantics: ParsePattern ( patternText, u, v ), https://tc39.es/ecma262/#sec-parsepattern -ThrowCompletionOr parse_regex_pattern(VM& vm, StringView pattern, bool unicode, bool unicode_sets) +ThrowCompletionOr parse_regex_pattern(VM& vm, StringView pattern, bool unicode, bool unicode_sets) { auto result = parse_regex_pattern(pattern, unicode, unicode_sets); if (result.is_error()) @@ -151,7 +151,7 @@ GC::Ref RegExpObject::create(Realm& realm) return realm.create(realm.intrinsics().regexp_prototype()); } -GC::Ref RegExpObject::create(Realm& realm, Regex regex, ByteString pattern, ByteString flags) +GC::Ref RegExpObject::create(Realm& realm, Regex regex, String pattern, String flags) { return realm.create(move(regex), move(pattern), move(flags), realm.intrinsics().regexp_prototype()); } @@ -179,7 +179,7 @@ static RegExpObject::Flags to_flag_bits(StringView flags) return flag_bits; } -RegExpObject::RegExpObject(Regex regex, ByteString pattern, ByteString flags, Object& prototype) +RegExpObject::RegExpObject(Regex regex, String pattern, String flags, Object& prototype) : Object(ConstructWithPrototypeTag::Tag, prototype) , m_pattern(move(pattern)) , m_flags(move(flags)) @@ -203,14 +203,14 @@ ThrowCompletionOr> RegExpObject::regexp_initialize(VM& vm, // 1. If pattern is undefined, let P be the empty String. // 2. Else, let P be ? ToString(pattern). auto pattern = pattern_value.is_undefined() - ? ByteString::empty() - : TRY(pattern_value.to_byte_string(vm)); + ? String {} + : TRY(pattern_value.to_string(vm)); // 3. If flags is undefined, let F be the empty String. // 4. Else, let F be ? ToString(flags). auto flags = flags_value.is_undefined() - ? ByteString::empty() - : TRY(flags_value.to_byte_string(vm)); + ? String {} + : TRY(flags_value.to_string(vm)); // 5. If F contains any code unit other than "d", "g", "i", "m", "s", "u", "v", or "y", or if F contains any code unit more than once, throw a SyntaxError exception. // 6. If F contains "i", let i be true; else let i be false. @@ -223,7 +223,7 @@ ThrowCompletionOr> RegExpObject::regexp_initialize(VM& vm, return vm.throw_completion(parsed_flags_or_error.release_error()); auto parsed_flags = parsed_flags_or_error.release_value(); - auto parsed_pattern = ByteString::empty(); + auto parsed_pattern = String {}; if (!pattern.is_empty()) { bool unicode = parsed_flags.has_flag_set(regex::ECMAScriptFlags::Unicode); bool unicode_sets = parsed_flags.has_flag_set(regex::ECMAScriptFlags::UnicodeSets); @@ -237,7 +237,7 @@ ThrowCompletionOr> RegExpObject::regexp_initialize(VM& vm, } // 14. If parseResult is a non-empty List of SyntaxError objects, throw a SyntaxError exception. - Regex regex(move(parsed_pattern), parsed_flags); + Regex regex(parsed_pattern.to_byte_string(), parsed_flags); if (regex.parser_result.error != regex::Error::NoError) return vm.throw_completion(ErrorType::RegExpCompileError, regex.error_string()); @@ -265,7 +265,7 @@ ThrowCompletionOr> RegExpObject::regexp_initialize(VM& vm, } // 22.2.6.13.1 EscapeRegExpPattern ( P, F ), https://tc39.es/ecma262/#sec-escaperegexppattern -ByteString RegExpObject::escape_regexp_pattern() const +String RegExpObject::escape_regexp_pattern() const { // 1. Let S be a String in the form of a Pattern[~UnicodeMode] (Pattern[+UnicodeMode] if F contains "u") equivalent // to P interpreted as UTF-16 encoded Unicode code points (6.1.4), in which certain code points are escaped as @@ -281,7 +281,7 @@ ByteString RegExpObject::escape_regexp_pattern() const // specification can be met by letting S be "(?:)". // 3. Return S. if (m_pattern.is_empty()) - return "(?:)"; + return "(?:)"_string; // FIXME: Check the 'u' and 'v' flags and escape accordingly StringBuilder builder; @@ -322,7 +322,7 @@ ByteString RegExpObject::escape_regexp_pattern() const } } - return builder.to_byte_string(); + return builder.to_string_without_validation(); } void RegExpObject::visit_edges(JS::Cell::Visitor& visitor) diff --git a/Libraries/LibJS/Runtime/RegExpObject.h b/Libraries/LibJS/Runtime/RegExpObject.h index 947a2b3bddb..32c1926dffa 100644 --- a/Libraries/LibJS/Runtime/RegExpObject.h +++ b/Libraries/LibJS/Runtime/RegExpObject.h @@ -18,12 +18,12 @@ namespace JS { ThrowCompletionOr> regexp_create(VM&, Value pattern, Value flags); ThrowCompletionOr> regexp_alloc(VM&, FunctionObject& new_target); -Result, ByteString> regex_flags_from_string(StringView flags); +Result, String> regex_flags_from_string(StringView flags); struct ParseRegexPatternError { - ByteString error; + String error; }; -ErrorOr parse_regex_pattern(StringView pattern, bool unicode, bool unicode_sets); -ThrowCompletionOr parse_regex_pattern(VM& vm, StringView pattern, bool unicode, bool unicode_sets); +ErrorOr parse_regex_pattern(StringView pattern, bool unicode, bool unicode_sets); +ThrowCompletionOr parse_regex_pattern(VM& vm, StringView pattern, bool unicode, bool unicode_sets); class RegExpObject : public Object { JS_OBJECT(RegExpObject, Object); @@ -51,16 +51,16 @@ public: }; static GC::Ref create(Realm&); - static GC::Ref create(Realm&, Regex regex, ByteString pattern, ByteString flags); + static GC::Ref create(Realm&, Regex regex, String pattern, String flags); ThrowCompletionOr> regexp_initialize(VM&, Value pattern, Value flags); - ByteString escape_regexp_pattern() const; + String escape_regexp_pattern() const; virtual void initialize(Realm&) override; virtual ~RegExpObject() override = default; - ByteString const& pattern() const { return m_pattern; } - ByteString const& flags() const { return m_flags; } + String const& pattern() const { return m_pattern; } + String const& flags() const { return m_flags; } Flags flag_bits() const { return m_flag_bits; } Regex const& regex() { return *m_regex; } Regex const& regex() const { return *m_regex; } @@ -72,12 +72,12 @@ public: private: RegExpObject(Object& prototype); - RegExpObject(Regex regex, ByteString pattern, ByteString flags, Object& prototype); + RegExpObject(Regex regex, String pattern, String flags, Object& prototype); virtual void visit_edges(Visitor&) override; - ByteString m_pattern; - ByteString m_flags; + String m_pattern; + String m_flags; Flags m_flag_bits { 0 }; bool m_legacy_features_enabled { false }; // [[LegacyFeaturesEnabled]] // Note: This is initialized in RegExpAlloc, but will be non-null afterwards diff --git a/Libraries/LibJS/Runtime/RegExpPrototype.cpp b/Libraries/LibJS/Runtime/RegExpPrototype.cpp index 54a6decbf5d..983b6de5333 100644 --- a/Libraries/LibJS/Runtime/RegExpPrototype.cpp +++ b/Libraries/LibJS/Runtime/RegExpPrototype.cpp @@ -99,7 +99,7 @@ static Value get_match_index_par(VM& vm, Utf16View const& string, Match const& m } // 22.2.7.8 MakeMatchIndicesIndexPairArray ( S, indices, groupNames, hasGroups ), https://tc39.es/ecma262/#sec-makematchindicesindexpairarray -static Value make_match_indices_index_pair_array(VM& vm, Utf16View const& string, Vector> const& indices, HashMap const& group_names, bool has_groups) +static Value make_match_indices_index_pair_array(VM& vm, Utf16View const& string, Vector> const& indices, HashMap const& group_names, bool has_groups) { // Note: This implementation differs from the spec, but has the same behavior. // @@ -186,7 +186,7 @@ static ThrowCompletionOr regexp_builtin_exec(VM& vm, RegExpObject& regexp // 5. If flags contains "y", let sticky be true; else let sticky be false. bool sticky = regex.options().has_flag_set(ECMAScriptFlags::Sticky); // 6. If flags contains "d", let hasIndices be true, else let hasIndices be false. - bool has_indices = regexp_object.flags().find('d').has_value(); + bool has_indices = regexp_object.flags().bytes_as_string_view().find('d').has_value(); // 7. If global is false and sticky is false, set lastIndex to 0. if (!global && !sticky) @@ -273,7 +273,7 @@ static ThrowCompletionOr regexp_builtin_exec(VM& vm, RegExpObject& regexp Vector captured_values; // 26. Let groupNames be a new empty List. - HashMap group_names; + HashMap group_names; // 27. Add match as the last element of indices. indices.append(move(match_indices)); diff --git a/Libraries/LibJS/Runtime/ShadowRealm.cpp b/Libraries/LibJS/Runtime/ShadowRealm.cpp index 35a6667abb5..76c6651818c 100644 --- a/Libraries/LibJS/Runtime/ShadowRealm.cpp +++ b/Libraries/LibJS/Runtime/ShadowRealm.cpp @@ -147,7 +147,7 @@ ThrowCompletionOr perform_shadow_realm_eval(VM& vm, StringView source_tex // 11. If result.[[Type]] is normal, then if (!eval_result.is_throw_completion()) { // a. Set result to the result of evaluating body. - auto maybe_executable = Bytecode::compile(vm, program, FunctionKind::Normal, "ShadowRealmEval"sv); + auto maybe_executable = Bytecode::compile(vm, program, FunctionKind::Normal, "ShadowRealmEval"_fly_string); if (maybe_executable.is_error()) { result = maybe_executable.release_error(); } else { @@ -211,7 +211,7 @@ ThrowCompletionOr shadow_realm_import_value(VM& vm, String specifier_stri auto referrer = GC::Ref { *eval_context->realm }; // 7. Perform HostLoadImportedModule(referrer, specifierString, empty, innerCapability). - vm.host_load_imported_module(referrer, ModuleRequest { specifier_string.to_byte_string() }, nullptr, inner_capability); + vm.host_load_imported_module(referrer, ModuleRequest { specifier_string }, nullptr, inner_capability); // 7. Suspend evalContext and remove it from the execution context stack. // NOTE: We don't support this concept yet. diff --git a/Libraries/LibJS/Runtime/StringOrSymbol.h b/Libraries/LibJS/Runtime/StringOrSymbol.h index 91df28c16d5..4803a323f1e 100644 --- a/Libraries/LibJS/Runtime/StringOrSymbol.h +++ b/Libraries/LibJS/Runtime/StringOrSymbol.h @@ -6,7 +6,7 @@ #pragma once -#include +#include #include #include #include @@ -20,7 +20,7 @@ public: { } - StringOrSymbol(DeprecatedFlyString const& string) + StringOrSymbol(FlyString const& string) : m_string(string) { } @@ -28,7 +28,7 @@ public: ~StringOrSymbol() { if (is_string()) - m_string.~DeprecatedFlyString(); + m_string.~FlyString(); } StringOrSymbol(Symbol const* symbol) @@ -40,7 +40,7 @@ public: StringOrSymbol(StringOrSymbol const& other) { if (other.is_string()) - new (&m_string) DeprecatedFlyString(other.m_string); + new (&m_string) FlyString(other.m_string); else m_bits = other.m_bits; } @@ -48,7 +48,7 @@ public: StringOrSymbol(StringOrSymbol&& other) { if (other.is_string()) - new (&m_string) DeprecatedFlyString(move(other.m_string)); + new (&m_string) FlyString(move(other.m_string)); else m_bits = exchange(other.m_bits, 0); } @@ -57,7 +57,7 @@ public: ALWAYS_INLINE bool is_symbol() const { return is_valid() && (m_bits & 2); } ALWAYS_INLINE bool is_string() const { return is_valid() && !(m_bits & 2); } - ALWAYS_INLINE DeprecatedFlyString as_string() const + ALWAYS_INLINE FlyString as_string() const { VERIFY(is_string()); return m_string; @@ -69,12 +69,12 @@ public: return reinterpret_cast(m_bits & ~2ULL); } - ByteString to_display_string() const + String to_display_string() const { if (is_string()) - return as_string(); + return as_string().to_string(); if (is_symbol()) - return as_symbol()->descriptive_string().release_value_but_fixme_should_propagate_errors().to_byte_string(); + return MUST(as_symbol()->descriptive_string()); VERIFY_NOT_REACHED(); } @@ -134,7 +134,7 @@ private: } union { - DeprecatedFlyString m_string; + FlyString m_string; Symbol const* m_symbol_with_tag; uintptr_t m_bits; }; diff --git a/Libraries/LibJS/Runtime/TypedArray.cpp b/Libraries/LibJS/Runtime/TypedArray.cpp index 0e70e4e7d52..b55ff62eb25 100644 --- a/Libraries/LibJS/Runtime/TypedArray.cpp +++ b/Libraries/LibJS/Runtime/TypedArray.cpp @@ -482,7 +482,7 @@ void TypedArrayBase::visit_edges(Visitor& visitor) { \ } \ \ - DeprecatedFlyString const& ClassName::element_name() const \ + FlyString const& ClassName::element_name() const \ { \ return vm().names.ClassName.as_string(); \ } \ diff --git a/Libraries/LibJS/Runtime/TypedArray.h b/Libraries/LibJS/Runtime/TypedArray.h index 162b5759abe..be6ce15e035 100644 --- a/Libraries/LibJS/Runtime/TypedArray.h +++ b/Libraries/LibJS/Runtime/TypedArray.h @@ -52,7 +52,7 @@ public: [[nodiscard]] Kind kind() const { return m_kind; } u32 element_size() const { return m_element_size; } - virtual DeprecatedFlyString const& element_name() const = 0; + virtual FlyString const& element_name() const = 0; // 25.1.3.11 IsUnclampedIntegerElementType ( type ), https://tc39.es/ecma262/#sec-isunclampedintegerelementtype virtual bool is_unclamped_integer_element_type() const = 0; @@ -526,7 +526,7 @@ ThrowCompletionOr compare_typed_array_elements(VM&, Value x, Value y, Fu static ThrowCompletionOr> create(Realm&, u32 length, FunctionObject& new_target); \ static ThrowCompletionOr> create(Realm&, u32 length); \ static GC::Ref create(Realm&, u32 length, ArrayBuffer& buffer); \ - virtual DeprecatedFlyString const& element_name() const override; \ + virtual FlyString const& element_name() const override; \ \ protected: \ ClassName(Object& prototype, u32 length, ArrayBuffer& array_buffer); \ diff --git a/Libraries/LibJS/Runtime/TypedArrayConstructor.cpp b/Libraries/LibJS/Runtime/TypedArrayConstructor.cpp index 9d16b623b1f..bfefd1acaac 100644 --- a/Libraries/LibJS/Runtime/TypedArrayConstructor.cpp +++ b/Libraries/LibJS/Runtime/TypedArrayConstructor.cpp @@ -13,7 +13,7 @@ namespace JS { GC_DEFINE_ALLOCATOR(TypedArrayConstructor); -TypedArrayConstructor::TypedArrayConstructor(DeprecatedFlyString const& name, Object& prototype) +TypedArrayConstructor::TypedArrayConstructor(FlyString const& name, Object& prototype) : NativeFunction(name, prototype) { } diff --git a/Libraries/LibJS/Runtime/TypedArrayConstructor.h b/Libraries/LibJS/Runtime/TypedArrayConstructor.h index 5fce614cb15..3490b86b8dc 100644 --- a/Libraries/LibJS/Runtime/TypedArrayConstructor.h +++ b/Libraries/LibJS/Runtime/TypedArrayConstructor.h @@ -23,7 +23,7 @@ public: virtual ThrowCompletionOr> construct(FunctionObject& new_target) override; protected: - TypedArrayConstructor(DeprecatedFlyString const& name, Object& prototype); + TypedArrayConstructor(FlyString const& name, Object& prototype); private: virtual bool has_constructor() const override { return true; } diff --git a/Libraries/LibJS/Runtime/VM.cpp b/Libraries/LibJS/Runtime/VM.cpp index 87e1b508558..d3c0e993dde 100644 --- a/Libraries/LibJS/Runtime/VM.cpp +++ b/Libraries/LibJS/Runtime/VM.cpp @@ -40,7 +40,7 @@ namespace JS { ErrorOr> VM::create(OwnPtr custom_data) { ErrorMessages error_messages {}; - error_messages[to_underlying(ErrorMessage::OutOfMemory)] = TRY(String::from_utf8(ErrorType::OutOfMemory.message())); + error_messages[to_underlying(ErrorMessage::OutOfMemory)] = ErrorType::OutOfMemory.message(); auto vm = adopt_ref(*new VM(move(custom_data), move(error_messages))); @@ -121,7 +121,7 @@ VM::VM(OwnPtr custom_data, ErrorMessages error_messages) }; host_get_supported_import_attributes = [&] { - return Vector { "type" }; + return Vector { "type"_string }; }; // 19.2.1.2 HostEnsureCanCompileStrings ( calleeRealm, parameterStrings, bodyString, direct ), https://tc39.es/ecma262/#sec-hostensurecancompilestrings @@ -276,7 +276,7 @@ void VM::gather_roots(HashMap& roots) } // 9.1.2.1 GetIdentifierReference ( env, name, strict ), https://tc39.es/ecma262/#sec-getidentifierreference -ThrowCompletionOr VM::get_identifier_reference(Environment* environment, DeprecatedFlyString name, bool strict, size_t hops) +ThrowCompletionOr VM::get_identifier_reference(Environment* environment, FlyString name, bool strict, size_t hops) { // 1. If env is the value null, then if (!environment) { @@ -310,7 +310,7 @@ ThrowCompletionOr VM::get_identifier_reference(Environment* environme } // 9.4.2 ResolveBinding ( name [ , env ] ), https://tc39.es/ecma262/#sec-resolvebinding -ThrowCompletionOr VM::resolve_binding(DeprecatedFlyString const& name, Environment* environment) +ThrowCompletionOr VM::resolve_binding(FlyString const& name, Environment* environment) { // 1. If env is not present or if env is undefined, then if (!environment) { @@ -522,7 +522,7 @@ ScriptOrModule VM::get_active_script_or_module() const return m_execution_context_stack[0]->script_or_module; } -VM::StoredModule* VM::get_stored_module(ImportedModuleReferrer const&, ByteString const& filename, ByteString const&) +VM::StoredModule* VM::get_stored_module(ImportedModuleReferrer const&, ByteString const& filename, String const&) { // Note the spec says: // If this operation is called multiple times with the same (referrer, specifier) pair and it performs @@ -632,7 +632,7 @@ void VM::load_imported_module(ImportedModuleReferrer referrer, ModuleRequest con return; } - ByteString module_type; + String module_type; for (auto& attribute : module_request.attributes) { if (attribute.key == "type"sv) { module_type = attribute.value; @@ -659,7 +659,7 @@ void VM::load_imported_module(ImportedModuleReferrer referrer, ModuleRequest con }); LexicalPath base_path { base_filename }; - auto filename = LexicalPath::absolute_path(base_path.dirname(), module_request.module_specifier); + auto filename = LexicalPath::absolute_path(base_path.dirname(), module_request.module_specifier.to_deprecated_fly_string()); dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] base path: '{}'", base_path); dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] initial filename: '{}'", filename); @@ -735,7 +735,7 @@ void VM::load_imported_module(ImportedModuleReferrer referrer, ModuleRequest con m_loaded_modules.empend( referrer, module->filename(), - ByteString {}, // Null type + String {}, // Null type make_root(*module), true); diff --git a/Libraries/LibJS/Runtime/VM.h b/Libraries/LibJS/Runtime/VM.h index d1575cea11e..299d291b9dc 100644 --- a/Libraries/LibJS/Runtime/VM.h +++ b/Libraries/LibJS/Runtime/VM.h @@ -9,7 +9,7 @@ #pragma once -#include +#include #include #include #include @@ -197,8 +197,8 @@ public: u32 execution_generation() const { return m_execution_generation; } void finish_execution_generation() { ++m_execution_generation; } - ThrowCompletionOr resolve_binding(DeprecatedFlyString const&, Environment* = nullptr); - ThrowCompletionOr get_identifier_reference(Environment*, DeprecatedFlyString, bool strict, size_t hops = 0); + ThrowCompletionOr resolve_binding(FlyString const&, Environment* = nullptr); + ThrowCompletionOr get_identifier_reference(Environment*, FlyString, bool strict, size_t hops = 0); // 5.2.3.2 Throw an Exception, https://tc39.es/ecma262/#sec-throw-an-exception template @@ -274,7 +274,7 @@ public: Function(SourceTextModule&)> host_get_import_meta_properties; Function host_finalize_import_meta; - Function()> host_get_supported_import_attributes; + Function()> host_get_supported_import_attributes; void set_dynamic_imports_allowed(bool value) { m_dynamic_imports_allowed = value; } @@ -335,12 +335,12 @@ private: struct StoredModule { ImportedModuleReferrer referrer; ByteString filename; - ByteString type; + String type; GC::Root module; bool has_once_started_linking { false }; }; - StoredModule* get_stored_module(ImportedModuleReferrer const& script_or_module, ByteString const& filename, ByteString const& type); + StoredModule* get_stored_module(ImportedModuleReferrer const& script_or_module, ByteString const& filename, String const& type); Vector m_loaded_modules; diff --git a/Libraries/LibJS/Runtime/Value.cpp b/Libraries/LibJS/Runtime/Value.cpp index 6da7a6b7ad8..9b6f12fbd52 100644 --- a/Libraries/LibJS/Runtime/Value.cpp +++ b/Libraries/LibJS/Runtime/Value.cpp @@ -912,7 +912,7 @@ ThrowCompletionOr Value::to_property_key(VM& vm) const } // 3. Return ! ToString(key). - return MUST(key.to_byte_string(vm)); + return MUST(key.to_string(vm)); } // 7.1.6 ToInt32 ( argument ), https://tc39.es/ecma262/#sec-toint32 diff --git a/Libraries/LibJS/Runtime/WrappedFunction.h b/Libraries/LibJS/Runtime/WrappedFunction.h index 9cdd0e798c8..93291000794 100644 --- a/Libraries/LibJS/Runtime/WrappedFunction.h +++ b/Libraries/LibJS/Runtime/WrappedFunction.h @@ -23,7 +23,7 @@ public: virtual ThrowCompletionOr internal_call(Value this_argument, ReadonlySpan arguments_list) override; // FIXME: Remove this (and stop inventing random internal slots that shouldn't exist, jeez) - virtual DeprecatedFlyString const& name() const override { return m_wrapped_target_function->name(); } + virtual FlyString const& name() const override { return m_wrapped_target_function->name(); } virtual Realm* realm() const override { return m_realm; } diff --git a/Libraries/LibJS/SourceTextModule.cpp b/Libraries/LibJS/SourceTextModule.cpp index 51558675a9f..af33db03f79 100644 --- a/Libraries/LibJS/SourceTextModule.cpp +++ b/Libraries/LibJS/SourceTextModule.cpp @@ -261,7 +261,7 @@ Result, Vector> SourceTextModule::parse(S } // 16.2.1.6.2 GetExportedNames ( [ exportStarSet ] ), https://tc39.es/ecma262/#sec-getexportednames -ThrowCompletionOr> SourceTextModule::get_exported_names(VM& vm, Vector export_star_set) +ThrowCompletionOr> SourceTextModule::get_exported_names(VM& vm, Vector export_star_set) { dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] get_export_names of {}", filename()); // 1. Assert: module.[[Status]] is not new. @@ -276,14 +276,14 @@ ThrowCompletionOr> SourceTextModule::get_exported_na // FIXME: How do we check that? // b. Return a new empty List. - return Vector {}; + return Vector {}; } // 4. Append module to exportStarSet. export_star_set.append(this); // 5. Let exportedNames be a new empty List. - Vector exported_names; + Vector exported_names; // 6. For each ExportEntry Record e of module.[[LocalExportEntries]], do for (auto& entry : m_local_export_entries) { @@ -443,7 +443,7 @@ ThrowCompletionOr SourceTextModule::initialize_environment(VM& vm) // Note: We just loop through them in step 21. // 20. Let declaredVarNames be a new empty List. - Vector declared_var_names; + Vector declared_var_names; // 21. For each element d of varDeclarations, do // a. For each element dn of the BoundNames of d, do @@ -497,9 +497,9 @@ ThrowCompletionOr SourceTextModule::initialize_environment(VM& vm) // 1. Let fo be InstantiateFunctionObject of d with arguments env and privateEnv. // NOTE: Special case if the function is a default export of an anonymous function // it has name "*default*" but internally should have name "default". - DeprecatedFlyString function_name = function_declaration.name(); + FlyString function_name = function_declaration.name(); if (function_name == ExportStatement::local_name_for_default) - function_name = "default"sv; + function_name = "default"_fly_string; auto function = ECMAScriptFunctionObject::create(realm(), function_name, function_declaration.source_text(), function_declaration.body(), function_declaration.parameters(), function_declaration.function_length(), function_declaration.local_variables_names(), environment, private_environment, function_declaration.kind(), function_declaration.is_strict_mode(), function_declaration.parsing_insights()); @@ -537,7 +537,7 @@ ThrowCompletionOr SourceTextModule::initialize_environment(VM& vm) } // 16.2.1.6.3 ResolveExport ( exportName [ , resolveSet ] ), https://tc39.es/ecma262/#sec-resolveexport -ThrowCompletionOr SourceTextModule::resolve_export(VM& vm, DeprecatedFlyString const& export_name, Vector resolve_set) +ThrowCompletionOr SourceTextModule::resolve_export(VM& vm, FlyString const& export_name, Vector resolve_set) { // 1. Assert: module.[[Status]] is not new. VERIFY(m_status != ModuleStatus::New); @@ -716,7 +716,7 @@ ThrowCompletionOr SourceTextModule::execute_module(VM& vm, GC::Ptr SourceTextModule::execute_module(VM& vm, GC::Ptrm_ecmascript_code, + realm(), "module code with top-level await"_fly_string, StringView {}, this->m_ecmascript_code, {}, 0, {}, environment(), nullptr, FunctionKind::Async, true, parsing_insights); module_wrapper_function->set_is_module_wrapper(true); diff --git a/Libraries/LibJS/SourceTextModule.h b/Libraries/LibJS/SourceTextModule.h index 5e2c37ac442..4eb06bf9fe6 100644 --- a/Libraries/LibJS/SourceTextModule.h +++ b/Libraries/LibJS/SourceTextModule.h @@ -25,8 +25,8 @@ public: Program const& parse_node() const { return *m_ecmascript_code; } - virtual ThrowCompletionOr> get_exported_names(VM& vm, Vector export_star_set) override; - virtual ThrowCompletionOr resolve_export(VM& vm, DeprecatedFlyString const& export_name, Vector resolve_set = {}) override; + virtual ThrowCompletionOr> get_exported_names(VM& vm, Vector export_star_set) override; + virtual ThrowCompletionOr resolve_export(VM& vm, FlyString const& export_name, Vector resolve_set = {}) override; Object* import_meta() { return m_import_meta; } void set_import_meta(Badge, Object* import_meta) { m_import_meta = import_meta; } diff --git a/Libraries/LibJS/SyntheticModule.cpp b/Libraries/LibJS/SyntheticModule.cpp index 511d24b9fc2..e3fccebfbea 100644 --- a/Libraries/LibJS/SyntheticModule.cpp +++ b/Libraries/LibJS/SyntheticModule.cpp @@ -18,7 +18,7 @@ namespace JS { GC_DEFINE_ALLOCATOR(SyntheticModule); // 1.2.1 CreateSyntheticModule ( exportNames, evaluationSteps, realm, hostDefined ), https://tc39.es/proposal-json-modules/#sec-createsyntheticmodule -SyntheticModule::SyntheticModule(Vector export_names, SyntheticModule::EvaluationFunction evaluation_steps, Realm& realm, StringView filename) +SyntheticModule::SyntheticModule(Vector export_names, SyntheticModule::EvaluationFunction evaluation_steps, Realm& realm, StringView filename) : Module(realm, filename) , m_export_names(move(export_names)) , m_evaluation_steps(move(evaluation_steps)) @@ -27,14 +27,14 @@ SyntheticModule::SyntheticModule(Vector export_names, Synth } // 1.2.3.1 GetExportedNames( exportStarSet ), https://tc39.es/proposal-json-modules/#sec-smr-getexportednames -ThrowCompletionOr> SyntheticModule::get_exported_names(VM&, Vector) +ThrowCompletionOr> SyntheticModule::get_exported_names(VM&, Vector) { // 1. Return module.[[ExportNames]]. return m_export_names; } // 1.2.3.2 ResolveExport( exportName, resolveSet ), https://tc39.es/proposal-json-modules/#sec-smr-resolveexport -ThrowCompletionOr SyntheticModule::resolve_export(VM&, DeprecatedFlyString const& export_name, Vector) +ThrowCompletionOr SyntheticModule::resolve_export(VM&, FlyString const& export_name, Vector) { // 1. If module.[[ExportNames]] does not contain exportName, return null. if (!m_export_names.contains_slow(export_name)) @@ -123,7 +123,7 @@ ThrowCompletionOr SyntheticModule::evaluate(VM& vm) } // 1.2.2 SetSyntheticModuleExport ( module, exportName, exportValue ), https://tc39.es/proposal-json-modules/#sec-setsyntheticmoduleexport -ThrowCompletionOr SyntheticModule::set_synthetic_module_export(DeprecatedFlyString const& export_name, Value export_value) +ThrowCompletionOr SyntheticModule::set_synthetic_module_export(FlyString const& export_name, Value export_value) { auto& vm = this->realm().vm(); @@ -139,11 +139,11 @@ GC::Ref SyntheticModule::create_default_export_synthetic_module // 1. Let closure be the a Abstract Closure with parameters (module) that captures defaultExport and performs the following steps when called: auto closure = [default_export = make_root(default_export)](SyntheticModule& module) -> ThrowCompletionOr { // a. Return ? module.SetSyntheticExport("default", defaultExport). - return module.set_synthetic_module_export("default", default_export.value()); + return module.set_synthetic_module_export("default"_fly_string, default_export.value()); }; // 2. Return CreateSyntheticModule("default", closure, realm) - return realm.heap().allocate(Vector { "default" }, move(closure), realm, filename); + return realm.heap().allocate(Vector { "default"_fly_string }, move(closure), realm, filename); } // 1.4 ParseJSONModule ( source ), https://tc39.es/proposal-json-modules/#sec-parse-json-module diff --git a/Libraries/LibJS/SyntheticModule.h b/Libraries/LibJS/SyntheticModule.h index a76002f5235..f960c7bedb6 100644 --- a/Libraries/LibJS/SyntheticModule.h +++ b/Libraries/LibJS/SyntheticModule.h @@ -20,19 +20,19 @@ public: static GC::Ref create_default_export_synthetic_module(Value default_export, Realm& realm, StringView filename); - ThrowCompletionOr set_synthetic_module_export(DeprecatedFlyString const& export_name, Value export_value); + ThrowCompletionOr set_synthetic_module_export(FlyString const& export_name, Value export_value); virtual ThrowCompletionOr link(VM& vm) override; virtual ThrowCompletionOr evaluate(VM& vm) override; - virtual ThrowCompletionOr> get_exported_names(VM& vm, Vector export_star_set) override; - virtual ThrowCompletionOr resolve_export(VM& vm, DeprecatedFlyString const& export_name, Vector resolve_set) override; + virtual ThrowCompletionOr> get_exported_names(VM& vm, Vector export_star_set) override; + virtual ThrowCompletionOr resolve_export(VM& vm, FlyString const& export_name, Vector resolve_set) override; virtual PromiseCapability& load_requested_modules(GC::Ptr) override; private: - SyntheticModule(Vector export_names, EvaluationFunction evaluation_steps, Realm& realm, StringView filename); + SyntheticModule(Vector export_names, EvaluationFunction evaluation_steps, Realm& realm, StringView filename); - Vector m_export_names; // [[ExportNames]] - EvaluationFunction m_evaluation_steps; // [[EvaluationSteps]] + Vector m_export_names; // [[ExportNames]] + EvaluationFunction m_evaluation_steps; // [[EvaluationSteps]] }; ThrowCompletionOr> parse_json_module(StringView source_text, Realm& realm, StringView filename); diff --git a/Libraries/LibJS/Token.h b/Libraries/LibJS/Token.h index 315acd9b572..16789830970 100644 --- a/Libraries/LibJS/Token.h +++ b/Libraries/LibJS/Token.h @@ -6,7 +6,7 @@ #pragma once -#include +#include #include #include #include @@ -208,16 +208,16 @@ public: { return m_value.visit( [](StringView view) { return view; }, - [](DeprecatedFlyString const& identifier) { return identifier.view(); }, + [](FlyString const& identifier) { return identifier.bytes_as_string_view(); }, [](Empty) -> StringView { VERIFY_NOT_REACHED(); }); } - DeprecatedFlyString DeprecatedFlyString_value() const + FlyString fly_string_value() const { return m_value.visit( - [](StringView view) -> DeprecatedFlyString { return view; }, - [](DeprecatedFlyString const& identifier) -> DeprecatedFlyString { return identifier; }, - [](Empty) -> DeprecatedFlyString { VERIFY_NOT_REACHED(); }); + [](StringView view) -> FlyString { return MUST(FlyString::from_utf8(view)); }, + [](FlyString const& identifier) -> FlyString { return identifier; }, + [](Empty) -> FlyString { VERIFY_NOT_REACHED(); }); } size_t line_number() const { return m_line_number; } @@ -236,7 +236,7 @@ public: ByteString string_value(StringValueStatus& status) const; ByteString raw_template_value() const; - void set_identifier_value(DeprecatedFlyString value) + void set_identifier_value(FlyString value) { m_value = move(value); } @@ -249,7 +249,7 @@ private: StringView m_message; StringView m_trivia; StringView m_original_value; - Variant m_value {}; + Variant m_value {}; size_t m_line_number { 0 }; size_t m_line_column { 0 }; size_t m_offset { 0 }; diff --git a/Libraries/LibRegex/RegexMatch.h b/Libraries/LibRegex/RegexMatch.h index 96c41b0df99..81110a82afe 100644 --- a/Libraries/LibRegex/RegexMatch.h +++ b/Libraries/LibRegex/RegexMatch.h @@ -12,7 +12,7 @@ #include #include -#include +#include #include #include #include @@ -476,7 +476,7 @@ private: class Match final { private: - Optional string; + Optional string; public: Match() = default; @@ -491,9 +491,9 @@ public: { } - Match(ByteString string_, size_t const line_, size_t const column_, size_t const global_offset_) + Match(String string_, size_t const line_, size_t const column_, size_t const global_offset_) : string(move(string_)) - , view(string.value().view()) + , view(string.value().bytes_as_string_view()) , line(line_) , column(column_) , global_offset(global_offset_) @@ -502,7 +502,7 @@ public: Match(RegexStringView const view_, StringView capture_group_name_, size_t const line_, size_t const column_, size_t const global_offset_) : view(view_) - , capture_group_name(capture_group_name_) + , capture_group_name(MUST(FlyString::from_utf8(capture_group_name_))) , line(line_) , column(column_) , global_offset(global_offset_) @@ -521,7 +521,7 @@ public: } RegexStringView view {}; - Optional capture_group_name {}; + Optional capture_group_name {}; size_t line { 0 }; size_t column { 0 }; size_t global_offset { 0 }; diff --git a/Libraries/LibRegex/RegexParser.cpp b/Libraries/LibRegex/RegexParser.cpp index b37ff67357a..e45b9c95a2e 100644 --- a/Libraries/LibRegex/RegexParser.cpp +++ b/Libraries/LibRegex/RegexParser.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include diff --git a/Libraries/LibRegex/RegexParser.h b/Libraries/LibRegex/RegexParser.h index 2118e21d022..eb8a8bce8be 100644 --- a/Libraries/LibRegex/RegexParser.h +++ b/Libraries/LibRegex/RegexParser.h @@ -11,6 +11,7 @@ #include "RegexLexer.h" #include "RegexOptions.h" +#include #include #include #include diff --git a/Libraries/LibWeb/Animations/KeyframeEffect.cpp b/Libraries/LibWeb/Animations/KeyframeEffect.cpp index b668b7d602d..e3b7b7d5ab9 100644 --- a/Libraries/LibWeb/Animations/KeyframeEffect.cpp +++ b/Libraries/LibWeb/Animations/KeyframeEffect.cpp @@ -185,7 +185,7 @@ static WebIDL::ExceptionOr> process_a_keyframe_like_object(JS:: // 1. Let raw value be the result of calling the [[Get]] internal method on keyframe input, with property name // as the property key and keyframe input as the receiver. // 2. Check the completion record of raw value. - JS::PropertyKey key { property_name.to_byte_string(), JS::PropertyKey::StringMayBeNumber::No }; + JS::PropertyKey key { property_name, JS::PropertyKey::StringMayBeNumber::No }; auto raw_value = TRY(keyframe_object.has_property(key)) ? TRY(keyframe_object.get(key)) : *all_value; using PropertyValuesType = Conditional, String>; @@ -827,7 +827,7 @@ WebIDL::ExceptionOr> KeyframeEffect::get_keyframes() for (auto const& [id, value] : keyframe.parsed_properties()) { auto value_string = JS::PrimitiveString::create(vm, value->to_string(CSS::CSSStyleValue::SerializationMode::Normal)); - TRY(object->set(JS::PropertyKey { DeprecatedFlyString(CSS::camel_case_string_from_property_id(id)), JS::PropertyKey::StringMayBeNumber::No }, value_string, ShouldThrowExceptions::Yes)); + TRY(object->set(JS::PropertyKey { CSS::camel_case_string_from_property_id(id), JS::PropertyKey::StringMayBeNumber::No }, value_string, ShouldThrowExceptions::Yes)); } m_keyframe_objects.append(object); diff --git a/Libraries/LibWeb/Bindings/MainThreadVM.cpp b/Libraries/LibWeb/Bindings/MainThreadVM.cpp index ba0569094a7..113a551d85f 100644 --- a/Libraries/LibWeb/Bindings/MainThreadVM.cpp +++ b/Libraries/LibWeb/Bindings/MainThreadVM.cpp @@ -369,7 +369,7 @@ ErrorOr initialize_main_thread_vm(HTML::EventLoop::Type type) // 2. Let url be the result of resolving a module specifier given moduleScript and specifier. auto url = TRY(Bindings::throw_dom_exception_if_needed(vm, [&] { - return HTML::resolve_module_specifier(*module_script, specifier_string.to_byte_string()); + return HTML::resolve_module_specifier(*module_script, specifier_string); })); // 3. Return the serialization of url. @@ -388,9 +388,9 @@ ErrorOr initialize_main_thread_vm(HTML::EventLoop::Type type) }; // 8.1.6.7.2 HostGetSupportedImportAttributes(), https://html.spec.whatwg.org/multipage/webappapis.html#hostgetsupportedimportassertions - s_main_thread_vm->host_get_supported_import_attributes = []() -> Vector { + s_main_thread_vm->host_get_supported_import_attributes = []() -> Vector { // 1. Return « "type" ». - return { "type"sv }; + return { "type"_string }; }; // 8.1.6.7.3 HostLoadImportedModule(referrer, moduleRequest, loadState, payload), https://html.spec.whatwg.org/multipage/webappapis.html#hostloadimportedmodule @@ -460,7 +460,7 @@ ErrorOr initialize_main_thread_vm(HTML::EventLoop::Type type) // 2. Resolve a module specifier given referencingScript and moduleRequest.[[Specifier]], catching any // exceptions. If they throw an exception, let resolutionError be the thrown exception. - auto maybe_exception = HTML::resolve_module_specifier(referencing_script, module_request.module_specifier); + auto maybe_exception = HTML::resolve_module_specifier(referencing_script, module_request.module_specifier.to_string()); // 3. If the previous step threw an exception, then: if (maybe_exception.is_exception()) { @@ -500,7 +500,7 @@ ErrorOr initialize_main_thread_vm(HTML::EventLoop::Type type) // 8. Let url be the result of resolving a module specifier given referencingScript and moduleRequest.[[Specifier]], // catching any exceptions. If they throw an exception, let resolutionError be the thrown exception. - auto url = HTML::resolve_module_specifier(referencing_script, module_request.module_specifier); + auto url = HTML::resolve_module_specifier(referencing_script, module_request.module_specifier.to_string()); // 9. If the previous step threw an exception, then: if (url.is_exception()) { diff --git a/Libraries/LibWeb/Bindings/PlatformObject.cpp b/Libraries/LibWeb/Bindings/PlatformObject.cpp index 252aa137e50..7d9549e42de 100644 --- a/Libraries/LibWeb/Bindings/PlatformObject.cpp +++ b/Libraries/LibWeb/Bindings/PlatformObject.cpp @@ -41,7 +41,7 @@ JS::ThrowCompletionOr PlatformObject::is_named_property_exposed_on_object( // 1. If P is not a supported property name of O, then return false. // NOTE: This is in it's own variable to enforce the type. - if (!is_supported_property_name(MUST(String::from_byte_string(property_key.to_string())))) + if (!is_supported_property_name(property_key.to_string())) return false; // 2. If O has an own property named P, then return false. @@ -118,7 +118,7 @@ JS::ThrowCompletionOr> PlatformObject::legacy_p // 1. If the result of running the named property visibility algorithm with property name P and object O is true, then: if (TRY(is_named_property_exposed_on_object(property_name))) { // FIXME: It's unfortunate that this is done twice, once in is_named_property_exposed_on_object and here. - auto property_name_string = MUST(FlyString::from_deprecated_fly_string(property_name.to_string())); + auto property_name_string = property_name.to_string(); // 1. Let operation be the operation used to declare the named property getter. // 2. Let value be an uninitialized variable. @@ -236,7 +236,7 @@ JS::ThrowCompletionOr PlatformObject::internal_set(JS::PropertyKey const& // 2. If O implements an interface with a named property setter and P is a String, then: if (m_legacy_platform_object_flags->has_named_property_setter && property_name.is_string()) { // 1. Invoke the named property setter on O with P and V. - TRY(throw_dom_exception_if_needed(vm, [&] { return invoke_named_property_setter(MUST(String::from_byte_string(property_name.as_string())), value); })); + TRY(throw_dom_exception_if_needed(vm, [&] { return invoke_named_property_setter(property_name.as_string(), value); })); // 2. Return true. return true; @@ -282,7 +282,7 @@ JS::ThrowCompletionOr PlatformObject::internal_define_own_property(JS::Pro // 2. If O supports named properties, O does not implement an interface with the [Global] extended attribute, P is a String, and P is not an unforgeable property name of O, then: // FIXME: Check if P is not an unforgeable property name of O if (m_legacy_platform_object_flags->supports_named_properties && !m_legacy_platform_object_flags->has_global_interface_extended_attribute && property_name.is_string()) { - auto const property_name_as_string = MUST(FlyString::from_deprecated_fly_string(property_name.as_string())); + auto const property_name_as_string = property_name.as_string(); // 1. Let creating be true if P is not a supported property name, and false otherwise. bool creating = !is_supported_property_name(property_name_as_string); @@ -360,7 +360,7 @@ JS::ThrowCompletionOr PlatformObject::internal_delete(JS::PropertyKey cons // 4. Otherwise, operation was defined with an identifier: // 1. Perform method steps of operation with O as this and « P » as the argument values. // 2. If operation was declared with a return type of boolean and the steps returned false, then return false. - auto did_deletion_fail = TRY(throw_dom_exception_if_needed(vm, [&] { return delete_value(MUST(String::from_byte_string(property_name_string))); })); + auto did_deletion_fail = TRY(throw_dom_exception_if_needed(vm, [&] { return delete_value(property_name_string); })); if (!m_legacy_platform_object_flags->named_property_deleter_has_identifier) VERIFY(did_deletion_fail != DidDeletionFail::NotRelevant); @@ -423,7 +423,7 @@ JS::ThrowCompletionOr> PlatformObject::internal_own_pr // 3. If O supports named properties, then for each P of O’s supported property names that is visible according to the named property visibility algorithm, append P to keys. if (m_legacy_platform_object_flags->supports_named_properties) { for (auto& named_property : supported_property_names()) { - if (TRY(is_named_property_exposed_on_object(named_property.to_deprecated_fly_string()))) + if (TRY(is_named_property_exposed_on_object(named_property))) keys.append(JS::PrimitiveString::create(vm, named_property)); } } diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp index 9d6f8659018..659b74a7a0c 100644 --- a/Libraries/LibWeb/DOM/Document.cpp +++ b/Libraries/LibWeb/DOM/Document.cpp @@ -4737,7 +4737,7 @@ void Document::start_intersection_observing_a_lazy_loading_element(Element& elem // 2. If doc's lazy load intersection observer is null, set it to a new IntersectionObserver instance, initialized as follows: if (!m_lazy_load_intersection_observer) { // - The callback is these steps, with arguments entries and observer: - auto callback = JS::NativeFunction::create(realm, "", [this](JS::VM& vm) -> JS::ThrowCompletionOr { + auto callback = JS::NativeFunction::create(realm, ""_fly_string, [this](JS::VM& vm) -> JS::ThrowCompletionOr { // For each entry in entries using a method of iteration which does not trigger developer-modifiable array accessors or iteration hooks: auto& entries = as(vm.argument(0).as_object()); auto entries_length = MUST(MUST(entries.get(vm.names.length)).to_length(vm)); diff --git a/Libraries/LibWeb/DOM/EventTarget.cpp b/Libraries/LibWeb/DOM/EventTarget.cpp index b013493126d..6960ed42853 100644 --- a/Libraries/LibWeb/DOM/EventTarget.cpp +++ b/Libraries/LibWeb/DOM/EventTarget.cpp @@ -513,7 +513,7 @@ WebIDL::CallbackType* EventTarget::get_current_value_of_event_handler(FlyString // 6. Return scope. (NOTE: Not necessary) - auto function = JS::ECMAScriptFunctionObject::create(realm, name.to_deprecated_fly_string(), builder.to_byte_string(), program->body(), program->parameters(), program->function_length(), program->local_variables_names(), scope, nullptr, JS::FunctionKind::Normal, program->is_strict_mode(), + auto function = JS::ECMAScriptFunctionObject::create(realm, name, builder.to_byte_string(), program->body(), program->parameters(), program->function_length(), program->local_variables_names(), scope, nullptr, JS::FunctionKind::Normal, program->is_strict_mode(), program->parsing_insights(), is_arrow_function); // 10. Remove settings object's realm execution context from the JavaScript execution context stack. diff --git a/Libraries/LibWeb/HTML/CrossOrigin/AbstractOperations.cpp b/Libraries/LibWeb/HTML/CrossOrigin/AbstractOperations.cpp index d02e2a11e27..e4076e3d33d 100644 --- a/Libraries/LibWeb/HTML/CrossOrigin/AbstractOperations.cpp +++ b/Libraries/LibWeb/HTML/CrossOrigin/AbstractOperations.cpp @@ -59,8 +59,8 @@ Vector cross_origin_properties(Variant property_names { - "window"sv, "self"sv, "location"sv, "close"sv, "closed"sv, "focus"sv, "blur"sv, "frames"sv, "length"sv, "top"sv, "opener"sv, "parent"sv, "postMessage"sv + static Array property_names { + "window"_fly_string, "self"_fly_string, "location"_fly_string, "close"_fly_string, "closed"_fly_string, "focus"_fly_string, "blur"_fly_string, "frames"_fly_string, "length"_fly_string, "top"_fly_string, "opener"_fly_string, "parent"_fly_string, "postMessage"_fly_string }; return (property_key.is_string() && any_of(property_names, [&](auto const& name) { return property_key.as_string() == name; })) || property_key.is_number(); } @@ -108,7 +108,7 @@ Optional cross_origin_get_own_property_helper(Variant CustomElementRegistry::define(String const& name, We // 4. For each callbackName of the keys of lifecycleCallbacks: for (auto const& callback_name : { CustomElementReactionNames::connectedCallback, CustomElementReactionNames::disconnectedCallback, CustomElementReactionNames::adoptedCallback, CustomElementReactionNames::attributeChangedCallback }) { // 1. Let callbackValue be ? Get(prototype, callbackName). - auto callback_value = TRY(prototype.get(callback_name.to_deprecated_fly_string())); + auto callback_value = TRY(prototype.get(callback_name)); // 2. If callbackValue is not undefined, then set the value of the entry in lifecycleCallbacks with key callbackName to the result of // converting callbackValue to the Web IDL Function callback type. @@ -259,7 +259,7 @@ JS::ThrowCompletionOr CustomElementRegistry::define(String const& name, We if (form_associated) { for (auto const& callback_name : { CustomElementReactionNames::formAssociatedCallback, CustomElementReactionNames::formResetCallback, CustomElementReactionNames::formDisabledCallback, CustomElementReactionNames::formStateRestoreCallback }) { // 1. Let callbackValue be ? Get(prototype, callbackName). - auto callback_value = TRY(prototype.get(callback_name.to_deprecated_fly_string())); + auto callback_value = TRY(prototype.get(callback_name)); // 2. If callbackValue is not undefined, then set lifecycleCallbacks[callbackName] to the result of converting callbackValue // to the Web IDL Function callback type. diff --git a/Libraries/LibWeb/HTML/HTMLAllCollection.cpp b/Libraries/LibWeb/HTML/HTMLAllCollection.cpp index 1c0b5e5ca12..02679f11459 100644 --- a/Libraries/LibWeb/HTML/HTMLAllCollection.cpp +++ b/Libraries/LibWeb/HTML/HTMLAllCollection.cpp @@ -118,7 +118,7 @@ Variant, GC::Ref, Empty> HTMLAllColle return Empty {}; // 2. Return the result of getting the "all"-indexed or named element(s) from this, given nameOrIndex. - return get_the_all_indexed_or_named_elements(name_or_index.value().to_deprecated_fly_string()); + return get_the_all_indexed_or_named_elements(name_or_index.value()); } // https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#dom-htmlallcollection-nameditem @@ -211,7 +211,7 @@ Variant, GC::Ref, Empty> HTMLAllColle } // 2. Return the result of getting the "all"-named element(s) from collection given nameOrIndex. - return get_the_all_named_elements(MUST(FlyString::from_deprecated_fly_string(name_or_index.as_string()))); + return get_the_all_named_elements(name_or_index.as_string()); } Optional HTMLAllCollection::item_value(size_t index) const diff --git a/Libraries/LibWeb/HTML/Scripting/Fetching.cpp b/Libraries/LibWeb/HTML/Scripting/Fetching.cpp index f19e34da093..807d92cfd2a 100644 --- a/Libraries/LibWeb/HTML/Scripting/Fetching.cpp +++ b/Libraries/LibWeb/HTML/Scripting/Fetching.cpp @@ -61,19 +61,19 @@ ScriptFetchOptions default_script_fetch_options() } // https://html.spec.whatwg.org/multipage/webappapis.html#module-type-from-module-request -ByteString module_type_from_module_request(JS::ModuleRequest const& module_request) +String module_type_from_module_request(JS::ModuleRequest const& module_request) { // 1. Let moduleType be "javascript". - ByteString module_type = "javascript"sv; + String module_type = "javascript"_string; // 2. If moduleRequest.[[Attributes]] has a Record entry such that entry.[[Key]] is "type", then: for (auto const& entry : module_request.attributes) { - if (entry.key != "type"sv) + if (entry.key != "type"_string) continue; // 1. If entry.[[Value]] is "javascript", then set moduleType to null. - if (entry.value == "javascript"sv) - module_type = nullptr; + if (entry.value == "javascript"_string) + module_type = ""_string; // FIXME: This should be null! // 2. Otherwise, set moduleType to entry.[[Value]]. else module_type = entry.value; @@ -85,7 +85,7 @@ ByteString module_type_from_module_request(JS::ModuleRequest const& module_reque // https://html.spec.whatwg.org/multipage/webappapis.html#resolve-a-module-specifier // https://whatpr.org/html/9893/webappapis.html#resolve-a-module-specifier -WebIDL::ExceptionOr resolve_module_specifier(Optional referring_script, ByteString const& specifier) +WebIDL::ExceptionOr resolve_module_specifier(Optional referring_script, String const& specifier) { auto& vm = Bindings::main_thread_vm(); @@ -124,10 +124,10 @@ WebIDL::ExceptionOr resolve_module_specifier(Optional referri auto serialized_base_url = base_url->serialize(); // 7. Let asURL be the result of resolving a URL-like module specifier given specifier and baseURL. - auto as_url = resolve_url_like_module_specifier(specifier, *base_url); + auto as_url = resolve_url_like_module_specifier(specifier.to_byte_string(), *base_url); // 8. Let normalizedSpecifier be the serialization of asURL, if asURL is non-null; otherwise, specifier. - auto normalized_specifier = as_url.has_value() ? as_url->serialize().to_byte_string() : specifier; + auto normalized_specifier = as_url.has_value() ? as_url->serialize() : specifier; // 9. Let result be a URL-or-null, initially null. Optional result; @@ -142,7 +142,7 @@ WebIDL::ExceptionOr resolve_module_specifier(Optional referri // 1. If scopePrefix is serializedBaseURL, or if scopePrefix ends with U+002F (/) and scopePrefix is a code unit prefix of serializedBaseURL, then: if (scope_prefix == serialized_base_url || (scope_prefix.ends_with('/') && Infra::is_code_unit_prefix(scope_prefix, serialized_base_url))) { // 1. Let scopeImportsMatch be the result of resolving an imports match given normalizedSpecifier, asURL, and scopeImports. - auto scope_imports_match = TRY(resolve_imports_match(normalized_specifier, as_url, scope_imports)); + auto scope_imports_match = TRY(resolve_imports_match(normalized_specifier.to_byte_string(), as_url, scope_imports)); // 2. If scopeImportsMatch is not null, then set result to scopeImportsMatch, and break. if (scope_imports_match.has_value()) { @@ -154,7 +154,7 @@ WebIDL::ExceptionOr resolve_module_specifier(Optional referri // 11. If result is null, set result be the result of resolving an imports match given normalizedSpecifier, asURL, and importMap's imports. if (!result.has_value()) - result = TRY(resolve_imports_match(normalized_specifier, as_url, import_map.imports())); + result = TRY(resolve_imports_match(normalized_specifier.to_byte_string(), as_url, import_map.imports())); // 12. If result is null, set it to asURL. // Spec-Note: By this point, if result was null, specifier wasn't remapped to anything by importMap, but it might have been able to be turned into a URL. @@ -164,7 +164,7 @@ WebIDL::ExceptionOr resolve_module_specifier(Optional referri // 13. If result is not null, then: if (result.has_value()) { // 1. Add module to resolved module set given realm, serializedBaseURL, normalizedSpecifier, and asURL. - add_module_to_resolved_module_set(*realm, serialized_base_url, MUST(String::from_byte_string(normalized_specifier)), as_url); + add_module_to_resolved_module_set(*realm, serialized_base_url, normalized_specifier, as_url); // 2. Return result. return result.release_value(); @@ -180,7 +180,7 @@ WebIDL::ExceptionOr> resolve_imports_match(ByteString const& // 1. For each specifierKey → resolutionResult of specifierMap: for (auto const& [specifier_key, resolution_result] : specifier_map) { // 1. If specifierKey is normalizedSpecifier, then: - if (specifier_key == normalized_specifier) { + if (specifier_key.bytes_as_string_view() == normalized_specifier) { // 1. If resolutionResult is null, then throw a TypeError indicating that resolution of specifierKey was blocked by a null entry. if (!resolution_result.has_value()) return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, String::formatted("Import resolution of '{}' was blocked by a null entry.", specifier_key).release_value_but_fixme_should_propagate_errors() }; @@ -193,7 +193,7 @@ WebIDL::ExceptionOr> resolve_imports_match(ByteString const& // 2. If all of the following are true: if ( // - specifierKey ends with U+002F (/); - specifier_key.ends_with("/"sv) && + specifier_key.bytes_as_string_view().ends_with("/"sv) && // - specifierKey is a code unit prefix of normalizedSpecifier; and Infra::is_code_unit_prefix(specifier_key, normalized_specifier) && // - either asURL is null, or asURL is special, @@ -207,7 +207,7 @@ WebIDL::ExceptionOr> resolve_imports_match(ByteString const& // 2. Assert: resolutionResult is a URL. // 3. Let afterPrefix be the portion of normalizedSpecifier after the initial specifierKey prefix. // FIXME: Clarify if this is meant by the portion after the initial specifierKey prefix. - auto after_prefix = normalized_specifier.substring(specifier_key.length()); + auto after_prefix = normalized_specifier.substring(specifier_key.bytes_as_string_view().length()); // 4. Assert: resolutionResult, serialized, ends with U+002F (/), as enforced during parsing. VERIFY(resolution_result->serialize().ends_with('/')); @@ -321,7 +321,7 @@ String resolve_a_module_integrity_metadata(const URL::URL& url, EnvironmentSetti // 2. If map's integrity[url] does not exist, then return the empty string. // 3. Return map's integrity[url]. - return MUST(String::from_byte_string(map.integrity().get(url).value_or(""))); + return map.integrity().get(url).value_or(""_string); } // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-classic-script @@ -623,7 +623,7 @@ void fetch_single_module_script(JS::Realm& realm, OnFetchScriptComplete on_complete) { // 1. Let moduleType be "javascript". - ByteString module_type = "javascript"sv; + String module_type = "javascript"_string; // 2. If moduleRequest was given, then set moduleType to the result of running the module type from module request steps given moduleRequest. if (module_request.has_value()) @@ -639,8 +639,8 @@ void fetch_single_module_script(JS::Realm& realm, // 5. If moduleMap[(url, moduleType)] is "fetching", wait in parallel until that entry's value changes, // then queue a task on the networking task source to proceed with running the following steps. - if (module_map.is_fetching(url, module_type)) { - module_map.wait_for_change(realm.heap(), url, module_type, [on_complete, &realm](auto entry) -> void { + if (module_map.is_fetching(url, module_type.to_byte_string())) { + module_map.wait_for_change(realm.heap(), url, module_type.to_byte_string(), [on_complete, &realm](auto entry) -> void { HTML::queue_global_task(HTML::Task::Source::Networking, realm.global_object(), GC::create_function(realm.heap(), [on_complete, entry] { // FIXME: This should run other steps, for now we just assume the script loaded. VERIFY(entry.type == ModuleMap::EntryType::ModuleScript || entry.type == ModuleMap::EntryType::Failed); @@ -653,14 +653,14 @@ void fetch_single_module_script(JS::Realm& realm, } // 6. If moduleMap[(url, moduleType)] exists, run onComplete given moduleMap[(url, moduleType)], and return. - auto entry = module_map.get(url, module_type); + auto entry = module_map.get(url, module_type.to_byte_string()); if (entry.has_value() && entry->type == ModuleMap::EntryType::ModuleScript) { on_complete->function()(entry->module_script); return; } // 7. Set moduleMap[(url, moduleType)] to "fetching". - module_map.set(url, module_type, { ModuleMap::EntryType::Fetching, nullptr }); + module_map.set(url, module_type.to_byte_string(), { ModuleMap::EntryType::Fetching, nullptr }); // 8. Let request be a new request whose URL is url, mode is "cors", referrer is referrer, and client is fetchClient. auto request = Fetch::Infrastructure::Request::create(realm.vm()); @@ -670,7 +670,7 @@ void fetch_single_module_script(JS::Realm& realm, request->set_client(&fetch_client); // 9. Set request's destination to the result of running the fetch destination from module type steps given destination and moduleType. - request->set_destination(fetch_destination_from_module_type(destination, module_type)); + request->set_destination(fetch_destination_from_module_type(destination, module_type.to_byte_string())); // 10. If destination is "worker", "sharedworker", or "serviceworker", and isTopLevel is true, then set request's mode to "same-origin". if ((destination == Fetch::Infrastructure::Request::Destination::Worker || destination == Fetch::Infrastructure::Request::Destination::SharedWorker || destination == Fetch::Infrastructure::Request::Destination::ServiceWorker) && is_top_level == TopLevelModule::Yes) @@ -691,7 +691,7 @@ void fetch_single_module_script(JS::Realm& realm, // - response's status is not an ok status, if (body_bytes.has() || body_bytes.has() || !Fetch::Infrastructure::is_ok_status(response->status())) { // then set moduleMap[(url, moduleType)] to null, run onComplete given null, and abort these steps. - module_map.set(url, module_type, { ModuleMap::EntryType::Failed, nullptr }); + module_map.set(url, module_type.to_byte_string(), { ModuleMap::EntryType::Failed, nullptr }); on_complete->function()(nullptr); return; } @@ -719,7 +719,7 @@ void fetch_single_module_script(JS::Realm& realm, // FIXME: 9. If mimeType is a JSON MIME type and moduleType is "json", then set moduleScript to the result of creating a JSON module script given sourceText and settingsObject. // 10. Set moduleMap[(url, moduleType)] to moduleScript, and run onComplete given moduleScript. - module_map.set(url, module_type, { ModuleMap::EntryType::ModuleScript, module_script }); + module_map.set(url, module_type.to_byte_string(), { ModuleMap::EntryType::ModuleScript, module_script }); on_complete->function()(module_script); }; diff --git a/Libraries/LibWeb/HTML/Scripting/Fetching.h b/Libraries/LibWeb/HTML/Scripting/Fetching.h index 6968d0e6efd..f4c6bbeff07 100644 --- a/Libraries/LibWeb/HTML/Scripting/Fetching.h +++ b/Libraries/LibWeb/HTML/Scripting/Fetching.h @@ -82,8 +82,8 @@ private: } }; -ByteString module_type_from_module_request(JS::ModuleRequest const&); -WebIDL::ExceptionOr resolve_module_specifier(Optional referring_script, ByteString const& specifier); +String module_type_from_module_request(JS::ModuleRequest const&); +WebIDL::ExceptionOr resolve_module_specifier(Optional referring_script, String const& specifier); WebIDL::ExceptionOr> resolve_imports_match(ByteString const& normalized_specifier, Optional as_url, ModuleSpecifierMap const&); Optional resolve_url_like_module_specifier(ByteString const& specifier, URL::URL const& base_url); ScriptFetchOptions get_descendant_script_fetch_options(ScriptFetchOptions const& original_options, URL::URL const& url, EnvironmentSettingsObject& settings_object); diff --git a/Libraries/LibWeb/HTML/Scripting/ImportMap.cpp b/Libraries/LibWeb/HTML/Scripting/ImportMap.cpp index 0da652ce3a9..ed19be8e39e 100644 --- a/Libraries/LibWeb/HTML/Scripting/ImportMap.cpp +++ b/Libraries/LibWeb/HTML/Scripting/ImportMap.cpp @@ -31,7 +31,7 @@ WebIDL::ExceptionOr parse_import_map_string(JS::Realm& realm, ByteStr auto& parsed_object = parsed.as_object(); // 3. Let sortedAndNormalizedImports be an empty ordered map. - ModuleSpecifierMap sorted_and_normalised_imports; + ModuleSpecifierMap sorted_and_normalized_imports; // 4. If parsed["imports"] exists, then: if (TRY(parsed_object.has_property("imports"_fly_string))) { @@ -42,11 +42,11 @@ WebIDL::ExceptionOr parse_import_map_string(JS::Realm& realm, ByteStr return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "The 'imports' top-level value of an importmap needs to be a JSON object."_string }; // Set sortedAndNormalizedImports to the result of sorting and normalizing a module specifier map given parsed["imports"] and baseURL. - sorted_and_normalised_imports = TRY(sort_and_normalise_module_specifier_map(realm, imports.as_object(), base_url)); + sorted_and_normalized_imports = TRY(sort_and_normalise_module_specifier_map(realm, imports.as_object(), base_url)); } // 5. Let sortedAndNormalizedScopes be an empty ordered map. - HashMap sorted_and_normalised_scopes; + HashMap sorted_and_normalized_scopes; // 6. If parsed["scopes"] exists, then: if (TRY(parsed_object.has_property("scopes"_fly_string))) { @@ -57,11 +57,11 @@ WebIDL::ExceptionOr parse_import_map_string(JS::Realm& realm, ByteStr return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "The 'scopes' top-level value of an importmap needs to be a JSON object."_string }; // Set sortedAndNormalizedScopes to the result of sorting and normalizing scopes given parsed["scopes"] and baseURL. - sorted_and_normalised_scopes = TRY(sort_and_normalise_scopes(realm, scopes.as_object(), base_url)); + sorted_and_normalized_scopes = TRY(sort_and_normalise_scopes(realm, scopes.as_object(), base_url)); } // 7. Let normalizedIntegrity be an empty ordered map. - ModuleIntegrityMap normalised_integrity; + ModuleIntegrityMap normalized_integrity; // 8. If parsed["integrity"] exists, then: if (TRY(parsed_object.has_property("integrity"_fly_string))) { @@ -72,7 +72,7 @@ WebIDL::ExceptionOr parse_import_map_string(JS::Realm& realm, ByteStr return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "The 'integrity' top-level value of an importmap needs to be a JSON object."_string }; // 2. Set normalizedIntegrity to the result of normalizing a module integrity map given parsed["integrity"] and baseURL. - normalised_integrity = TRY(normalize_module_integrity_map(realm, integrity.as_object(), base_url)); + normalized_integrity = TRY(normalize_module_integrity_map(realm, integrity.as_object(), base_url)); } // 9. If parsed's keys contains any items besides "imports", "scopes", or "integrity", then the user agent should report a warning to the console indicating that an invalid top-level key was present in the import map. @@ -86,14 +86,14 @@ WebIDL::ExceptionOr parse_import_map_string(JS::Realm& realm, ByteStr // 10. Return an import map whose imports are sortedAndNormalizedImports, whose scopes are sortedAndNormalizedScopes, and whose integrity are normalizedIntegrity. ImportMap import_map; - import_map.set_imports(sorted_and_normalised_imports); - import_map.set_scopes(sorted_and_normalised_scopes); - import_map.set_integrity(normalised_integrity); + import_map.set_imports(sorted_and_normalized_imports); + import_map.set_scopes(sorted_and_normalized_scopes); + import_map.set_integrity(normalized_integrity); return import_map; } // https://html.spec.whatwg.org/multipage/webappapis.html#normalizing-a-specifier-key -Optional normalise_specifier_key(JS::Realm& realm, DeprecatedFlyString specifier_key, URL::URL base_url) +Optional normalize_specifier_key(JS::Realm& realm, FlyString specifier_key, URL::URL base_url) { // 1. If specifierKey is the empty string, then: if (specifier_key.is_empty()) { @@ -102,15 +102,15 @@ Optional normalise_specifier_key(JS::Realm& realm, Deprecat console.output_debug_message(JS::Console::LogLevel::Warn, "Specifier keys may not be empty"sv); // 2. Return null. - return Optional {}; + return Optional {}; } // 2. Let url be the result of resolving a URL-like module specifier, given specifierKey and baseURL. - auto url = resolve_url_like_module_specifier(specifier_key, base_url); + auto url = resolve_url_like_module_specifier(specifier_key.to_string().to_byte_string(), base_url); // 3. If url is not null, then return the serialization of url. if (url.has_value()) - return url->serialize().to_byte_string(); + return url->serialize(); // 4. Return specifierKey. return specifier_key; @@ -120,17 +120,17 @@ Optional normalise_specifier_key(JS::Realm& realm, Deprecat WebIDL::ExceptionOr sort_and_normalise_module_specifier_map(JS::Realm& realm, JS::Object& original_map, URL::URL base_url) { // 1. Let normalized be an empty ordered map. - ModuleSpecifierMap normalised; + ModuleSpecifierMap normalized; // 2. For each specifierKey → value of originalMap: for (auto& specifier_key : original_map.shape().property_table().keys()) { auto value = TRY(original_map.get(specifier_key.as_string())); // 1. Let normalizedSpecifierKey be the result of normalizing a specifier key given specifierKey and baseURL. - auto normalised_specifier_key = normalise_specifier_key(realm, specifier_key.as_string(), base_url); + auto normalized_specifier_key = normalize_specifier_key(realm, specifier_key.as_string(), base_url); // 2. If normalizedSpecifierKey is null, then continue. - if (!normalised_specifier_key.has_value()) + if (!normalized_specifier_key.has_value()) continue; // 3. If value is not a string, then: @@ -140,7 +140,7 @@ WebIDL::ExceptionOr sort_and_normalise_module_specifier_map( console.output_debug_message(JS::Console::LogLevel::Warn, "Addresses need to be strings"sv); // 2. Set normalized[normalizedSpecifierKey] to null. - normalised.set(normalised_specifier_key.value(), {}); + normalized.set(normalized_specifier_key.value().to_string(), {}); // 3. Continue. continue; @@ -156,39 +156,39 @@ WebIDL::ExceptionOr sort_and_normalise_module_specifier_map( console.output_debug_message(JS::Console::LogLevel::Warn, "Address was invalid"sv); // 2. Set normalized[normalizedSpecifierKey] to null. - normalised.set(normalised_specifier_key.value(), {}); + normalized.set(normalized_specifier_key.value().to_string(), {}); // 3. Continue. continue; } // 6. If specifierKey ends with U+002F (/), and the serialization of addressURL does not end with U+002F (/), then: - if (specifier_key.as_string().ends_with("/"sv) && !address_url->serialize().ends_with('/')) { + if (specifier_key.as_string().bytes_as_string_view().ends_with("/"sv) && !address_url->serialize().ends_with('/')) { // 1. The user agent may report a warning to the console indicating that an invalid address was given for the specifier key specifierKey; since specifierKey ends with a slash, the address needs to as well. auto& console = realm.intrinsics().console_object()->console(); console.output_debug_message(JS::Console::LogLevel::Warn, MUST(String::formatted("An invalid address was given for the specifier key ({}); since specifierKey ends with a slash, the address needs to as well", specifier_key.as_string()))); // 2. Set normalized[normalizedSpecifierKey] to null. - normalised.set(normalised_specifier_key.value(), {}); + normalized.set(normalized_specifier_key.value().to_string(), {}); // 3. Continue. continue; } // 7. Set normalized[normalizedSpecifierKey] to addressURL. - normalised.set(normalised_specifier_key.value(), address_url.value()); + normalized.set(normalized_specifier_key.value().to_string(), address_url.value()); } // 3. Return the result of sorting in descending order normalized, with an entry a being less than an entry b if a's key is code unit less than b's key. - return normalised; + return normalized; } // https://html.spec.whatwg.org/multipage/webappapis.html#sorting-and-normalizing-scopes WebIDL::ExceptionOr> sort_and_normalise_scopes(JS::Realm& realm, JS::Object& original_map, URL::URL base_url) { // 1. Let normalized be an empty ordered map. - HashMap normalised; + HashMap normalized; // 2. For each scopePrefix → potentialSpecifierMap of originalMap: for (auto& scope_prefix : original_map.shape().property_table().keys()) { @@ -214,25 +214,25 @@ WebIDL::ExceptionOr> sort_and_normalise_sc // 4. Let normalizedScopePrefix be the serialization of scopePrefixURL. // 5. Set normalized[normalizedScopePrefix] to the result of sorting and normalizing a module specifier map given potentialSpecifierMap and baseURL. - normalised.set(scope_prefix_url.value(), TRY(sort_and_normalise_module_specifier_map(realm, potential_specifier_map.as_object(), base_url))); + normalized.set(scope_prefix_url.value(), TRY(sort_and_normalise_module_specifier_map(realm, potential_specifier_map.as_object(), base_url))); } // 3. Return the result of sorting in descending order normalized, with an entry a being less than an entry b if a's key is code unit less than b's key. - return normalised; + return normalized; } // https://html.spec.whatwg.org/multipage/webappapis.html#normalizing-a-module-integrity-map WebIDL::ExceptionOr normalize_module_integrity_map(JS::Realm& realm, JS::Object& original_map, URL::URL base_url) { // 1. Let normalized be an empty ordered map. - ModuleIntegrityMap normalised; + ModuleIntegrityMap normalized; // 2. For each key → value of originalMap: for (auto& key : original_map.shape().property_table().keys()) { auto value = TRY(original_map.get(key.as_string())); // 1. Let resolvedURL be the result of resolving a URL-like module specifier given key and baseURL. - auto resolved_url = resolve_url_like_module_specifier(key.as_string(), base_url); + auto resolved_url = resolve_url_like_module_specifier(key.as_string().to_string().to_byte_string(), base_url); // 2. If resolvedURL is null, then: if (!resolved_url.has_value()) { @@ -257,11 +257,11 @@ WebIDL::ExceptionOr normalize_module_integrity_map(JS::Realm } // 4. Set normalized[resolvedURL] to value. - normalised.set(resolved_url.release_value(), value.as_string().byte_string()); + normalized.set(resolved_url.release_value(), value.as_string().utf8_string()); } // 3. Return normalized. - return normalised; + return normalized; } // https://html.spec.whatwg.org/multipage/webappapis.html#merge-module-specifier-maps @@ -316,13 +316,13 @@ void merge_existing_and_new_import_maps(Window& global, ImportMap& new_import_ma // 1. If scopePrefix is record's serialized base URL, or if scopePrefix ends with U+002F (/) and scopePrefix is a code unit prefix of record's serialized base URL, then: if (scope_prefix.to_string() == record.serialized_base_url || (scope_prefix.to_string().ends_with('/') && record.serialized_base_url.has_value() && Infra::is_code_unit_prefix(scope_prefix.to_string(), *record.serialized_base_url))) { // 1. For each specifierKey → resolutionResult of scopeImports: - scope_imports.remove_all_matching([&](ByteString const& specifier_key, Optional const&) { + scope_imports.remove_all_matching([&](String const& specifier_key, Optional const&) { // 1. If specifierKey is record's specifier, or if all of the following conditions are true: // * specifierKey ends with U+002F (/); // * specifierKey is a code unit prefix of record's specifier; // * either record's specifier as a URL is null or is special, // then: - if (specifier_key.view() == record.specifier + if (specifier_key.bytes_as_string_view() == record.specifier || (specifier_key.ends_with('/') && Infra::is_code_unit_prefix(specifier_key, record.specifier) && record.specifier_is_null_or_url_like_that_is_special)) { @@ -373,9 +373,9 @@ void merge_existing_and_new_import_maps(Window& global, ImportMap& new_import_ma // 6. For each record of global's resolved module set: for (auto const& record : global.resolved_module_set()) { // 1. For each specifier → url of newImportMapImports: - new_import_map_imports.remove_all_matching([&](ByteString const& specifier, Optional const&) { + new_import_map_imports.remove_all_matching([&](String const& specifier, Optional const&) { // 1. If specifier starts with record's specifier, then: - if (specifier.starts_with(record.specifier)) { + if (specifier.bytes_as_string_view().starts_with(record.specifier)) { // 1. The user agent may report a warning to the console indicating the ignored rule. They may choose to // avoid reporting if the rule is identical to an existing one. auto& console = realm.intrinsics().console_object()->console(); diff --git a/Libraries/LibWeb/HTML/Scripting/ImportMap.h b/Libraries/LibWeb/HTML/Scripting/ImportMap.h index 77a133edbfd..1ddbe061128 100644 --- a/Libraries/LibWeb/HTML/Scripting/ImportMap.h +++ b/Libraries/LibWeb/HTML/Scripting/ImportMap.h @@ -13,8 +13,8 @@ namespace Web::HTML { -using ModuleSpecifierMap = HashMap>; -using ModuleIntegrityMap = HashMap; +using ModuleSpecifierMap = HashMap>; +using ModuleIntegrityMap = HashMap; // https://html.spec.whatwg.org/multipage/webappapis.html#import-map class ImportMap { @@ -40,7 +40,7 @@ private: }; WebIDL::ExceptionOr parse_import_map_string(JS::Realm& realm, ByteString const& input, URL::URL base_url); -Optional normalise_specifier_key(JS::Realm& realm, DeprecatedFlyString specifier_key, URL::URL base_url); +Optional normalize_specifier_key(JS::Realm& realm, FlyString specifier_key, URL::URL base_url); WebIDL::ExceptionOr sort_and_normalise_module_specifier_map(JS::Realm& realm, JS::Object& original_map, URL::URL base_url); WebIDL::ExceptionOr> sort_and_normalise_scopes(JS::Realm& realm, JS::Object& original_map, URL::URL base_url); WebIDL::ExceptionOr normalize_module_integrity_map(JS::Realm& realm, JS::Object& original_map, URL::URL base_url); diff --git a/Libraries/LibWeb/HTML/StructuredSerialize.cpp b/Libraries/LibWeb/HTML/StructuredSerialize.cpp index bcdfe6e1e00..edeb09ec261 100644 --- a/Libraries/LibWeb/HTML/StructuredSerialize.cpp +++ b/Libraries/LibWeb/HTML/StructuredSerialize.cpp @@ -521,8 +521,8 @@ WebIDL::ExceptionOr serialize_reg_exp_object(JS::VM& vm, SerializationReco // Note: A Regex object is perfectly happy to be reconstructed with just the source+flags // In the future, we could optimize the work being done on the deserialize step by serializing // more of the internal state (the [[RegExpMatcher]] internal slot) - TRY(serialize_string(vm, serialized, TRY_OR_THROW_OOM(vm, String::from_byte_string(regexp_object.pattern())))); - TRY(serialize_string(vm, serialized, TRY_OR_THROW_OOM(vm, String::from_byte_string(regexp_object.flags())))); + TRY(serialize_string(vm, serialized, regexp_object.pattern())); + TRY(serialize_string(vm, serialized, regexp_object.flags())); return {}; } @@ -684,8 +684,8 @@ WebIDL::ExceptionOr serialize_viewed_array_buffer(JS::VM& vm, Vector& // [[ArrayBufferSerialized]]: bufferSerialized, [[ByteLength]]: value.[[ByteLength]], // [[ByteOffset]]: value.[[ByteOffset]], [[ArrayLength]]: value.[[ArrayLength]] }. serialize_enum(vector, ValueTag::ArrayBufferView); - vector.extend(move(buffer_serialized)); // [[ArrayBufferSerialized]] - TRY(serialize_string(vm, vector, view.element_name())); // [[Constructor]] + vector.extend(move(buffer_serialized)); // [[ArrayBufferSerialized]] + TRY(serialize_string(vm, vector, view.element_name().to_string())); // [[Constructor]] serialize_primitive_type(vector, JS::typed_array_byte_length(view_record)); serialize_primitive_type(vector, view.byte_offset()); serialize_primitive_type(vector, JS::typed_array_length(view_record)); diff --git a/Libraries/LibWeb/HTML/Window.cpp b/Libraries/LibWeb/HTML/Window.cpp index a5a37752a58..18e2edeb1c9 100644 --- a/Libraries/LibWeb/HTML/Window.cpp +++ b/Libraries/LibWeb/HTML/Window.cpp @@ -740,9 +740,9 @@ WebIDL::ExceptionOr Window::initialize_web_interfaces(Badge(realm), JS::default_attributes); + define_direct_property("processes"_fly_string, realm.create(realm), JS::default_attributes); else if (path == "settings"sv) - define_direct_property("settings", realm.create(realm), JS::default_attributes); + define_direct_property("settings"_fly_string, realm.create(realm), JS::default_attributes); } return {}; diff --git a/Libraries/LibWeb/HTML/WindowProxy.cpp b/Libraries/LibWeb/HTML/WindowProxy.cpp index 104d4da0997..a2ba643a4e8 100644 --- a/Libraries/LibWeb/HTML/WindowProxy.cpp +++ b/Libraries/LibWeb/HTML/WindowProxy.cpp @@ -119,7 +119,7 @@ JS::ThrowCompletionOr> WindowProxy::internal_ge auto navigable_property_set = m_window->document_tree_child_navigable_target_name_property_set(); auto property_key_string = property_key.to_string(); - if (auto navigable = navigable_property_set.get(property_key_string.view()); navigable.has_value()) { + if (auto navigable = navigable_property_set.get(property_key_string); navigable.has_value()) { // 1. Let value be the active WindowProxy of the named object of W with the name P. auto value = navigable.value()->active_window_proxy(); diff --git a/Libraries/LibWeb/Infra/JSON.cpp b/Libraries/LibWeb/Infra/JSON.cpp index eb453cfd3f6..93e97677883 100644 --- a/Libraries/LibWeb/Infra/JSON.cpp +++ b/Libraries/LibWeb/Infra/JSON.cpp @@ -137,7 +137,7 @@ WebIDL::ExceptionOr serialize_javascript_value_to_json_bytes(JS::VM& auto map_value_js_value = convert_an_infra_value_to_a_json_compatible_javascript_value(realm, map_entry.value); // 3. Perform ! CreateDataPropertyOrThrow(jsValue, mapKey, mapValueJSValue). - MUST(js_value->create_data_property_or_throw(map_entry.key.to_byte_string(), map_value_js_value)); + MUST(js_value->create_data_property_or_throw(map_entry.key, map_value_js_value)); } // 6. Return jsValue. diff --git a/Libraries/LibWeb/WebAssembly/Instance.cpp b/Libraries/LibWeb/WebAssembly/Instance.cpp index a1382a727d4..9598effdbd3 100644 --- a/Libraries/LibWeb/WebAssembly/Instance.cpp +++ b/Libraries/LibWeb/WebAssembly/Instance.cpp @@ -54,7 +54,7 @@ void Instance::initialize(JS::Realm& realm) [&](Wasm::FunctionAddress const& address) { Optional> object = m_function_instances.get(address); if (!object.has_value()) { - object = Detail::create_native_function(vm, address, export_.name(), this); + object = Detail::create_native_function(vm, address, MUST(String::from_byte_string(export_.name())), this); m_function_instances.set(address, *object); } diff --git a/Libraries/LibWeb/WebAssembly/WebAssembly.cpp b/Libraries/LibWeb/WebAssembly/WebAssembly.cpp index 209bf82bf9c..68ff1f99d36 100644 --- a/Libraries/LibWeb/WebAssembly/WebAssembly.cpp +++ b/Libraries/LibWeb/WebAssembly/WebAssembly.cpp @@ -372,7 +372,7 @@ JS::ThrowCompletionOr> compile_a_webass GC_DEFINE_ALLOCATOR(ExportedWasmFunction); -GC::Ref ExportedWasmFunction::create(JS::Realm& realm, DeprecatedFlyString const& name, Function(JS::VM&)> behavior, Wasm::FunctionAddress exported_address) +GC::Ref ExportedWasmFunction::create(JS::Realm& realm, FlyString const& name, Function(JS::VM&)> behavior, Wasm::FunctionAddress exported_address) { auto& vm = realm.vm(); auto prototype = realm.intrinsics().function_prototype(); @@ -383,13 +383,13 @@ GC::Ref ExportedWasmFunction::create(JS::Realm& realm, Dep prototype); } -ExportedWasmFunction::ExportedWasmFunction(DeprecatedFlyString name, GC::Ptr(JS::VM&)>> behavior, Wasm::FunctionAddress exported_address, JS::Object& prototype) +ExportedWasmFunction::ExportedWasmFunction(FlyString name, GC::Ptr(JS::VM&)>> behavior, Wasm::FunctionAddress exported_address, JS::Object& prototype) : NativeFunction(move(name), move(behavior), prototype) , m_exported_address(exported_address) { } -JS::NativeFunction* create_native_function(JS::VM& vm, Wasm::FunctionAddress address, ByteString const& name, Instance* instance) +JS::NativeFunction* create_native_function(JS::VM& vm, Wasm::FunctionAddress address, String const& name, Instance* instance) { auto& realm = *vm.current_realm(); Optional type; @@ -545,7 +545,7 @@ JS::Value to_js_value(JS::VM& vm, Wasm::Value& wasm_value, Wasm::ValueType type) [](Wasm::HostFunction& host_function) { return host_function.name(); }); - return create_native_function(vm, address, name); + return create_native_function(vm, address, MUST(String::from_byte_string(name))); } case Wasm::ValueType::ExternReference: { auto ref_ = wasm_value.to(); diff --git a/Libraries/LibWeb/WebAssembly/WebAssembly.h b/Libraries/LibWeb/WebAssembly/WebAssembly.h index 8e26f89aae1..45ff067db9b 100644 --- a/Libraries/LibWeb/WebAssembly/WebAssembly.h +++ b/Libraries/LibWeb/WebAssembly/WebAssembly.h @@ -71,13 +71,13 @@ class ExportedWasmFunction final : public JS::NativeFunction { GC_DECLARE_ALLOCATOR(ExportedWasmFunction); public: - static GC::Ref create(JS::Realm&, DeprecatedFlyString const& name, ESCAPING Function(JS::VM&)>, Wasm::FunctionAddress); + static GC::Ref create(JS::Realm&, FlyString const& name, ESCAPING Function(JS::VM&)>, Wasm::FunctionAddress); virtual ~ExportedWasmFunction() override = default; Wasm::FunctionAddress exported_address() const { return m_exported_address; } protected: - ExportedWasmFunction(DeprecatedFlyString name, GC::Ptr(JS::VM&)>>, Wasm::FunctionAddress, Object& prototype); + ExportedWasmFunction(FlyString name, GC::Ptr(JS::VM&)>>, Wasm::FunctionAddress, Object& prototype); private: Wasm::FunctionAddress m_exported_address; @@ -87,7 +87,7 @@ WebAssemblyCache& get_cache(JS::Realm&); JS::ThrowCompletionOr> instantiate_module(JS::VM&, Wasm::Module const&, GC::Ptr import_object); JS::ThrowCompletionOr> compile_a_webassembly_module(JS::VM&, ByteBuffer); -JS::NativeFunction* create_native_function(JS::VM&, Wasm::FunctionAddress address, ByteString const& name, Instance* instance = nullptr); +JS::NativeFunction* create_native_function(JS::VM&, Wasm::FunctionAddress address, String const& name, Instance* instance = nullptr); JS::ThrowCompletionOr to_webassembly_value(JS::VM&, JS::Value value, Wasm::ValueType const& type); Wasm::Value default_webassembly_value(JS::VM&, Wasm::ValueType type); JS::Value to_js_value(JS::VM&, Wasm::Value& wasm_value, Wasm::ValueType type); diff --git a/Libraries/LibWeb/WebDriver/Contexts.cpp b/Libraries/LibWeb/WebDriver/Contexts.cpp index c1654da914b..7bc96dfc52f 100644 --- a/Libraries/LibWeb/WebDriver/Contexts.cpp +++ b/Libraries/LibWeb/WebDriver/Contexts.cpp @@ -14,10 +14,10 @@ namespace Web::WebDriver { // https://w3c.github.io/webdriver/#dfn-web-window-identifier -static JS::PropertyKey const WEB_WINDOW_IDENTIFIER { "window-fcc6-11e5-b4f8-330a88ab9d7f" }; +static JS::PropertyKey const WEB_WINDOW_IDENTIFIER { "window-fcc6-11e5-b4f8-330a88ab9d7f"_fly_string }; // https://w3c.github.io/webdriver/#dfn-web-frame-identifier -static JS::PropertyKey const WEB_FRAME_IDENTIFIER { "frame-075b-4da1-b6ba-e579c2d3230a" }; +static JS::PropertyKey const WEB_FRAME_IDENTIFIER { "frame-075b-4da1-b6ba-e579c2d3230a"_fly_string }; // https://w3c.github.io/webdriver/#dfn-windowproxy-reference-object JsonObject window_proxy_reference_object(HTML::WindowProxy const& window) diff --git a/Libraries/LibWeb/WebDriver/ElementReference.cpp b/Libraries/LibWeb/WebDriver/ElementReference.cpp index b409103f825..6c6cf30df70 100644 --- a/Libraries/LibWeb/WebDriver/ElementReference.cpp +++ b/Libraries/LibWeb/WebDriver/ElementReference.cpp @@ -26,11 +26,11 @@ namespace Web::WebDriver { // https://w3c.github.io/webdriver/#dfn-web-element-identifier static String const web_element_identifier = "element-6066-11e4-a52e-4f735466cecf"_string; -static JS::PropertyKey web_element_identifier_key { web_element_identifier.to_byte_string() }; +static JS::PropertyKey web_element_identifier_key { web_element_identifier }; // https://w3c.github.io/webdriver/#dfn-shadow-root-identifier static String const shadow_root_identifier = "shadow-6066-11e4-a52e-4f735466cecf"_string; -static JS::PropertyKey shadow_root_identifier_key { shadow_root_identifier.to_byte_string() }; +static JS::PropertyKey shadow_root_identifier_key { shadow_root_identifier }; // https://w3c.github.io/webdriver/#dfn-browsing-context-group-node-map static HashMap, HashTable> browsing_context_group_node_map; diff --git a/Libraries/LibWeb/WebDriver/ExecuteScript.cpp b/Libraries/LibWeb/WebDriver/ExecuteScript.cpp index a25e56c8ebd..45c0c6652ff 100644 --- a/Libraries/LibWeb/WebDriver/ExecuteScript.cpp +++ b/Libraries/LibWeb/WebDriver/ExecuteScript.cpp @@ -67,7 +67,7 @@ static JS::ThrowCompletionOr execute_a_function_body(HTML::BrowsingCo // The result of parsing global scope above. // strict // The result of parsing strict above. - auto function = JS::ECMAScriptFunctionObject::create(realm, "", move(source_text), function_expression->body(), function_expression->parameters(), function_expression->function_length(), function_expression->local_variables_names(), &global_scope, nullptr, function_expression->kind(), function_expression->is_strict_mode(), function_expression->parsing_insights()); + auto function = JS::ECMAScriptFunctionObject::create(realm, ""_fly_string, move(source_text), function_expression->body(), function_expression->parameters(), function_expression->function_length(), function_expression->local_variables_names(), &global_scope, nullptr, function_expression->kind(), function_expression->is_strict_mode(), function_expression->parsing_insights()); // 9. Let completion be Function.[[Call]](window, parameters) with function as the this value. // NOTE: This is not entirely clear, but I don't think they mean actually passing `function` as diff --git a/Libraries/LibWeb/WebIDL/ExceptionOr.h b/Libraries/LibWeb/WebIDL/ExceptionOr.h index 0cd58c1426c..c7a39e8992d 100644 --- a/Libraries/LibWeb/WebIDL/ExceptionOr.h +++ b/Libraries/LibWeb/WebIDL/ExceptionOr.h @@ -170,7 +170,7 @@ struct Formatter : Formatter { if (value.is_object()) { auto& object = value.as_object(); - static const JS::PropertyKey message_property_key { "message" }; + static const JS::PropertyKey message_property_key { "message"_fly_string }; auto has_message_or_error = object.has_own_property(message_property_key); if (!has_message_or_error.is_error() && has_message_or_error.value()) { auto message_object = object.get_without_side_effects(message_property_key); diff --git a/Libraries/LibWeb/WebIDL/OverloadResolution.cpp b/Libraries/LibWeb/WebIDL/OverloadResolution.cpp index f7202713347..a110ef9e1d1 100644 --- a/Libraries/LibWeb/WebIDL/OverloadResolution.cpp +++ b/Libraries/LibWeb/WebIDL/OverloadResolution.cpp @@ -228,7 +228,7 @@ JS::ThrowCompletionOr resolve_overload(JS::VM& vm, IDL::Effect // then remove from S all other entries. else if (value.is_object() && value.as_object().is_typed_array() && has_overload_with_argument_type_or_subtype_matching(overloads, i, [&](IDL::Type const& type) { - if (type.is_plain() && (type.name() == static_cast(value.as_object()).element_name() || type.name() == "BufferSource" || type.name() == "ArrayBufferView")) + if (type.is_plain() && (type.name() == static_cast(value.as_object()).element_name().bytes_as_string_view() || type.name() == "BufferSource" || type.name() == "ArrayBufferView")) return true; if (type.is_object()) return true; diff --git a/Meta/Lagom/Fuzzers/FuzzilliJs.cpp b/Meta/Lagom/Fuzzers/FuzzilliJs.cpp index 2300130ff90..9c3ef8daa57 100644 --- a/Meta/Lagom/Fuzzers/FuzzilliJs.cpp +++ b/Meta/Lagom/Fuzzers/FuzzilliJs.cpp @@ -177,8 +177,8 @@ JS_DEFINE_NATIVE_FUNCTION(TestRunnerGlobalObject::fuzzilli) void TestRunnerGlobalObject::initialize(JS::Realm& realm) { Base::initialize(realm); - define_direct_property("global", this, JS::Attribute::Enumerable); - define_native_function(realm, "fuzzilli", fuzzilli, 2, JS::default_attributes); + define_direct_property("global"_fly_string, this, JS::Attribute::Enumerable); + define_native_function(realm, "fuzzilli"_fly_string, fuzzilli, 2, JS::default_attributes); } int main(int, char**) diff --git a/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp b/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp index 48b4b275691..98c00457d9a 100644 --- a/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp +++ b/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp @@ -1889,7 +1889,7 @@ static void generate_wrap_statement(SourceGenerator& generator, ByteString const // 2. For each key → value of D: for (auto const& [key, value] : @value@) { // 1. Let jsKey be key converted to a JavaScript value. - auto js_key = JS::PropertyKey { key.to_byte_string() }; + auto js_key = JS::PropertyKey { key }; // 2. Let jsValue be value converted to a JavaScript value. )~~~"); @@ -3263,7 +3263,7 @@ JS::ThrowCompletionOr> @named_properties_class@ // 4. If the result of running the named property visibility algorithm with property name P and object object is true, then: if (TRY(object.is_named_property_exposed_on_object(property_name))) { - auto property_name_string = MUST(FlyString::from_deprecated_fly_string(property_name.to_string())); + auto property_name_string = property_name.to_string(); // 1. Let operation be the operation used to declare the named property getter. // 2. Let value be an uninitialized variable. @@ -4179,7 +4179,7 @@ JS_DEFINE_NATIVE_FUNCTION(@class_name@::@attribute.setter_callback@) auto value = vm.argument(0); auto receiver = TRY(throw_dom_exception_if_needed(vm, [&]() { return impl->@attribute.cpp_name@(); })); - TRY(receiver->set(JS::PropertyKey { "@put_forwards_identifier@", JS::PropertyKey::StringMayBeNumber::No }, value, JS::Object::ShouldThrowExceptions::Yes)); + TRY(receiver->set(JS::PropertyKey { "@put_forwards_identifier@"_fly_string, JS::PropertyKey::StringMayBeNumber::No }, value, JS::Object::ShouldThrowExceptions::Yes)); return JS::js_undefined(); } @@ -4818,7 +4818,7 @@ namespace Web::Bindings { GC_DEFINE_ALLOCATOR(@constructor_class@); @constructor_class@::@constructor_class@(JS::Realm& realm) - : NativeFunction("@name@"sv, realm.intrinsics().function_prototype()) + : NativeFunction("@name@"_fly_string, realm.intrinsics().function_prototype()) { } diff --git a/Tests/LibJS/test-js.cpp b/Tests/LibJS/test-js.cpp index ee263d40dd9..99ef62cc848 100644 --- a/Tests/LibJS/test-js.cpp +++ b/Tests/LibJS/test-js.cpp @@ -71,7 +71,7 @@ TESTJS_GLOBAL_FUNCTION(mark_as_garbage, markAsGarbage) if (!outer_environment.has_value()) return vm.throw_completion(JS::ErrorType::UnknownIdentifier, variable_name.byte_string()); - auto reference = TRY(vm.resolve_binding(variable_name.byte_string(), outer_environment.value()->lexical_environment)); + auto reference = TRY(vm.resolve_binding(variable_name.utf8_string(), outer_environment.value()->lexical_environment)); auto value = TRY(reference.get_value(vm)); diff --git a/Tests/LibWasm/test-wasm.cpp b/Tests/LibWasm/test-wasm.cpp index d40c79632a5..926614f80bd 100644 --- a/Tests/LibWasm/test-wasm.cpp +++ b/Tests/LibWasm/test-wasm.cpp @@ -178,7 +178,7 @@ TESTJS_GLOBAL_FUNCTION(parse_webassembly_module, parseWebAssemblyModule) auto& module_object = static_cast(value.as_object()); for (auto& entry : module_object.module_instance().exports()) { // FIXME: Don't pretend that everything is a function - imports.set({ property.key.as_string(), entry.name(), Wasm::TypeIndex(0) }, entry.value()); + imports.set({ property.key.as_string().to_string().to_byte_string(), entry.name(), Wasm::TypeIndex(0) }, entry.value()); } } } diff --git a/Utilities/js.cpp b/Utilities/js.cpp index d0fd6a5cdd0..5faef4307f6 100644 --- a/Utilities/js.cpp +++ b/Utilities/js.cpp @@ -692,8 +692,8 @@ ErrorOr serenity_main(Main::Arguments arguments) CompleteProperty, } mode { Initial }; - StringView variable_name; - StringView property_name; + FlyString variable_name; + FlyString property_name; // we're only going to complete either // - @@ -720,7 +720,7 @@ ErrorOr serenity_main(Main::Arguments arguments) if (js_token.is_identifier_name()) { // ... mode = CompleteProperty; - property_name = js_token.value(); + property_name = js_token.fly_string_value(); } else { mode = Initial; } @@ -731,7 +731,7 @@ ErrorOr serenity_main(Main::Arguments arguments) if (js_token.type() == JS::TokenType::Identifier) { // ...... mode = CompleteVariable; - variable_name = js_token.value(); + variable_name = js_token.fly_string_value(); } else { mode = Initial; } @@ -743,7 +743,7 @@ ErrorOr serenity_main(Main::Arguments arguments) if (mode == CompleteNullProperty) { mode = CompleteProperty; - property_name = ""sv; + property_name = ""_fly_string; last_token_has_trivia = false; // [tab] is sensible to complete. } @@ -757,10 +757,10 @@ ErrorOr serenity_main(Main::Arguments arguments) if (!descriptor.key.is_string()) continue; auto key = descriptor.key.as_string(); - if (key.view().starts_with(property_pattern)) { + if (key.bytes_as_string_view().starts_with(property_pattern)) { Line::CompletionSuggestion completion { key, Line::CompletionSuggestion::ForSearch }; if (!results.contains_slow(completion)) { // hide duplicates - results.append(ByteString(key)); + results.append(key.to_string().to_byte_string()); results.last().invariant_offset = property_pattern.length(); } } @@ -794,9 +794,9 @@ ErrorOr serenity_main(Main::Arguments arguments) list_all_properties(variable.shape(), variable_name); for (auto const& name : global_environment.declarative_record().bindings()) { - if (name.starts_with(variable_name)) { - results.empend(name); - results.last().invariant_offset = variable_name.length(); + if (name.bytes_as_string_view().starts_with(variable_name)) { + results.empend(name.to_deprecated_fly_string()); + results.last().invariant_offset = variable_name.bytes().size(); } }