From 941faf9164b1f68da660e093a5697fefc2923022 Mon Sep 17 00:00:00 2001 From: Micha Reiser Date: Mon, 6 Jun 2022 12:58:27 +0200 Subject: [PATCH] refactor(formatter): Introduce `write`, `format`, and `format_args` macros (#2634) > tldr: Rust's allocation free `format`, `write` and `format_args` for Rome formatter! First of all, I'm sorry for this massive PR. The motivation behind this PR is to change our formatting to work from left to right. Something that may become useful when formatting comments. The current formatter formats the most-grouped elements first rather than left to right, mainly because all IR elements like `group_elements`, `fill` etc. accept a `FormatElement` as a parameter and not a `Format` implementation. The other motivation behind this PR is to make all formatting macros allocation free compared to the current `formatted!` and `format_elements` macro that requires at least one allocation (except the compiler optimises it away). This PR enforces left to right formatting by changing Format's signature from: ```rust fn format(&self, f: &Formatter) -> FormatResult ``` to ```rust fn format(&self, f: &mut Formatter) -> FormatResult() ``` The main change is that `format` no longer returns the formatted result but instead writes it into the `Formatter`, similar to Rust's `Debug` and `Display` trait with the `write` and `format_args` macros. The fact that `format` now writes to a shared `FormatElement` buffer enforces format rules to write the element in order or they will appear out of order in the output. Second, the PR changes all builders (`group_elements`, `fill`, `space`) to return objects that implement `Format` rather than `FormatElement`s directly. This decouples the formatting DSL from the IR used by the printer. The other added benefit is that builders that accept some inner content no longer accept `FormatElement` but instead accept any object implementing `Format`. This should remove the need for many `formatted!` calls that were necessary just because some helper needs a `FormatElement` because it's the least common denominator. OK, but how do I write my formatting logic now: ```rust impl FormatNodeFields for FormatNodeRule { fn format_fields( node: &JsFunctionBody, f: &mut Formatter, ) -> FormatResult<()> { let JsFunctionBodyFields { l_curly_token, directives, statements, r_curly_token, } = node.as_fields(); let format_statements = format_with(|f| { let mut join = f.join_nodes_with_hardline(); for stmt in &statements { join.entry(stmt.syntax(), &stmt.format_or_verbatim()); } join.finish() }); write!( f, [f.delimited( &l_curly_token?, &format_args![directives.format(), format_statements], &r_curly_token?, ) .block_indent()] ) } } ``` The main differences are * You call `write!(f, [])` instead of `formatted` if you want to write something to the document. * You use `format_args` if you want to pass multiple `Format` objects to a helper like `group_elements`. * The formatter now exposes helpers like `f.join()`, `f.join_with()`, `f.fill()` and `f.join_nodes_with_softline_break` etc to format a sequence of objects Part of #2571 --- crates/rome_formatter/src/arguments.rs | 154 ++ crates/rome_formatter/src/buffer.rs | 438 ++++ crates/rome_formatter/src/builders.rs | 1755 ++++++++++++++++- crates/rome_formatter/src/format_element.rs | 1396 +------------ .../rome_formatter/src/format_extensions.rs | 358 +--- crates/rome_formatter/src/formatter.rs | 246 ++- crates/rome_formatter/src/intersperse.rs | 72 - crates/rome_formatter/src/lib.rs | 445 +++-- crates/rome_formatter/src/macros.rs | 420 ++-- crates/rome_formatter/src/prelude.rs | 7 +- crates/rome_formatter/src/printer/mod.rs | 279 +-- crates/rome_js_formatter/README.md | 36 +- .../docs/implement_the_formatter.md | 30 +- crates/rome_js_formatter/src/builders.rs | 690 +++++++ crates/rome_js_formatter/src/context.rs | 2 +- crates/rome_js_formatter/src/cst.rs | 6 +- crates/rome_js_formatter/src/formatter.rs | 764 ------- crates/rome_js_formatter/src/generated.rs | 782 ++++---- .../any/array_assignment_pattern_element.rs | 15 +- .../js/any/array_binding_pattern_element.rs | 17 +- .../src/js/any/array_element.rs | 8 +- .../src/js/any/arrow_function_parameters.rs | 13 +- .../src/js/any/assignment.rs | 28 +- .../src/js/any/assignment_pattern.rs | 15 +- .../rome_js_formatter/src/js/any/binding.rs | 6 +- .../src/js/any/binding_pattern.rs | 12 +- .../src/js/any/call_argument.rs | 6 +- crates/rome_js_formatter/src/js/any/class.rs | 63 +- .../src/js/any/class_member.rs | 46 +- .../src/js/any/class_member_name.rs | 14 +- .../src/js/any/constructor_parameter.rs | 17 +- .../src/js/any/declaration.rs | 34 +- .../src/js/any/declaration_clause.rs | 49 +- .../src/js/any/export_clause.rs | 34 +- .../src/js/any/export_default_declaration.rs | 15 +- .../src/js/any/export_named_specifier.rs | 11 +- .../src/js/any/expression.rs | 86 +- .../src/js/any/for_in_or_of_initializer.rs | 13 +- .../src/js/any/for_initializer.rs | 8 +- .../src/js/any/formal_parameter.rs | 8 +- .../rome_js_formatter/src/js/any/function.rs | 98 +- .../src/js/any/function_body.rs | 6 +- .../src/js/any/import_assertion_entry.rs | 13 +- .../src/js/any/import_clause.rs | 14 +- .../src/js/any/in_property.rs | 6 +- .../src/js/any/literal_expression.rs | 29 +- .../src/js/any/method_modifier.rs | 10 +- .../src/js/any/module_item.rs | 8 +- crates/rome_js_formatter/src/js/any/name.rs | 6 +- .../src/js/any/named_import.rs | 10 +- .../src/js/any/named_import_specifier.rs | 15 +- .../any/object_assignment_pattern_member.rs | 15 +- .../js/any/object_binding_pattern_member.rs | 19 +- .../src/js/any/object_member.rs | 20 +- .../src/js/any/object_member_name.rs | 13 +- .../rome_js_formatter/src/js/any/parameter.rs | 8 +- .../src/js/any/property_modifier.rs | 19 +- crates/rome_js_formatter/src/js/any/root.rs | 8 +- .../rome_js_formatter/src/js/any/statement.rs | 72 +- .../src/js/any/switch_clause.rs | 6 +- .../src/js/any/template_element.rs | 8 +- .../assignments/array_assignment_pattern.rs | 22 +- .../array_assignment_pattern_rest_element.rs | 9 +- .../js/assignments/assignment_with_default.rs | 12 +- .../assignments/computed_member_assignment.rs | 12 +- .../js/assignments/identifier_assignment.rs | 8 +- .../assignments/object_assignment_pattern.rs | 21 +- .../object_assignment_pattern_property.rs | 22 +- .../object_assignment_pattern_rest.rs | 8 +- ...t_assignment_pattern_shorthand_property.rs | 21 +- .../assignments/parenthesized_assignment.rs | 10 +- .../assignments/static_member_assignment.rs | 11 +- .../src/js/auxiliary/array_hole.rs | 4 +- .../src/js/auxiliary/case_clause.rs | 40 +- .../src/js/auxiliary/catch_clause.rs | 34 +- .../src/js/auxiliary/default_clause.rs | 31 +- .../src/js/auxiliary/directive.rs | 17 +- .../src/js/auxiliary/else_clause.rs | 9 +- .../src/js/auxiliary/expression_snipped.rs | 13 +- .../src/js/auxiliary/finally_clause.rs | 12 +- .../src/js/auxiliary/function_body.rs | 21 +- .../src/js/auxiliary/initializer_clause.rs | 12 +- .../src/js/auxiliary/module.rs | 25 +- .../src/js/auxiliary/name.rs | 6 +- .../src/js/auxiliary/new_target.rs | 8 +- .../src/js/auxiliary/private_name.rs | 6 +- .../src/js/auxiliary/reference_identifier.rs | 9 +- .../src/js/auxiliary/script.rs | 21 +- .../src/js/auxiliary/spread.rs | 6 +- .../src/js/auxiliary/static_modifier.rs | 8 +- .../auxiliary/variable_declaration_clause.rs | 14 +- .../src/js/auxiliary/variable_declarator.rs | 21 +- .../src/js/bindings/array_binding_pattern.rs | 22 +- .../array_binding_pattern_rest_element.rs | 10 +- .../bindings/binding_pattern_with_default.rs | 11 +- .../src/js/bindings/constructor_parameters.rs | 22 +- .../src/js/bindings/formal_parameter.rs | 16 +- .../src/js/bindings/identifier_binding.rs | 9 +- .../src/js/bindings/object_binding_pattern.rs | 22 +- .../object_binding_pattern_property.rs | 20 +- .../bindings/object_binding_pattern_rest.rs | 9 +- ...ject_binding_pattern_shorthand_property.rs | 23 +- .../src/js/bindings/parameters.rs | 19 +- .../src/js/bindings/rest_parameter.rs | 11 +- .../js/classes/constructor_class_member.rs | 10 +- .../src/js/classes/empty_class_member.rs | 8 +- .../src/js/classes/extends_clause.rs | 13 +- .../src/js/classes/getter_class_member.rs | 10 +- .../src/js/classes/method_class_member.rs | 23 +- .../src/js/classes/property_class_member.rs | 26 +- .../src/js/classes/setter_class_member.rs | 10 +- ...tatic_initialization_block_class_member.rs | 27 +- .../src/js/declarations/catch_declaration.rs | 18 +- .../src/js/declarations/class_declaration.rs | 9 +- .../class_export_default_declaration.rs | 9 +- .../declarations/for_variable_declaration.rs | 11 +- .../js/declarations/function_declaration.rs | 9 +- .../function_export_default_declaration.rs | 9 +- .../js/declarations/variable_declaration.rs | 11 +- .../src/js/expressions/array_expression.rs | 27 +- .../expressions/arrow_function_expression.rs | 8 +- .../js/expressions/assignment_expression.rs | 22 +- .../src/js/expressions/await_expression.rs | 11 +- .../expressions/big_int_literal_expression.rs | 21 +- .../src/js/expressions/binary_expression.rs | 5 +- .../expressions/boolean_literal_expression.rs | 9 +- .../src/js/expressions/call_arguments.rs | 26 +- .../src/js/expressions/call_expression.rs | 5 +- .../src/js/expressions/class_expression.rs | 9 +- .../expressions/computed_member_expression.rs | 44 +- .../js/expressions/conditional_expression.rs | 7 +- .../src/js/expressions/function_expression.rs | 9 +- .../js/expressions/identifier_expression.rs | 9 +- .../js/expressions/import_call_expression.rs | 9 +- .../src/js/expressions/in_expression.rs | 5 +- .../js/expressions/instanceof_expression.rs | 5 +- .../src/js/expressions/logical_expression.rs | 5 +- .../src/js/expressions/new_expression.rs | 25 +- .../js/expressions/null_literal_expression.rs | 9 +- .../expressions/number_literal_expression.rs | 9 +- .../src/js/expressions/object_expression.rs | 40 +- .../expressions/parenthesized_expression.rs | 70 +- .../js/expressions/post_update_expression.rs | 8 +- .../js/expressions/pre_update_expression.rs | 8 +- .../expressions/regex_literal_expression.rs | 18 +- .../src/js/expressions/sequence_expression.rs | 177 +- .../expressions/static_member_expression.rs | 161 +- .../expressions/string_literal_expression.rs | 45 +- .../src/js/expressions/super_expression.rs | 8 +- .../src/js/expressions/template.rs | 16 +- .../js/expressions/template_chunk_element.rs | 5 +- .../src/js/expressions/template_element.rs | 5 +- .../src/js/expressions/this_expression.rs | 8 +- .../src/js/expressions/unary_expression.rs | 41 +- .../src/js/expressions/yield_argument.rs | 11 +- .../src/js/expressions/yield_expression.rs | 8 +- .../array_assignment_pattern_element_list.rs | 10 +- .../array_binding_pattern_element_list.rs | 10 +- .../src/js/lists/array_element_list.rs | 28 +- .../src/js/lists/call_argument_list.rs | 9 +- .../src/js/lists/class_member_list.rs | 10 +- .../src/js/lists/constructor_modifier_list.rs | 12 +- .../js/lists/constructor_parameter_list.rs | 12 +- .../src/js/lists/directive_list.rs | 67 +- .../lists/export_named_from_specifier_list.rs | 12 +- .../js/lists/export_named_specifier_list.rs | 12 +- .../js/lists/import_assertion_entry_list.rs | 12 +- .../src/js/lists/method_modifier_list.rs | 9 +- .../src/js/lists/module_item_list.rs | 10 +- .../js/lists/named_import_specifier_list.rs | 12 +- ...object_assignment_pattern_property_list.rs | 17 +- .../object_binding_pattern_property_list.rs | 17 +- .../src/js/lists/object_member_list.rs | 15 +- .../src/js/lists/parameter_list.rs | 14 +- .../src/js/lists/property_modifier_list.rs | 12 +- .../src/js/lists/statement_list.rs | 10 +- .../src/js/lists/switch_case_list.rs | 10 +- .../src/js/lists/template_element_list.rs | 17 +- .../src/js/lists/variable_declarator_list.rs | 76 +- .../src/js/module/default_import_specifier.rs | 11 +- .../rome_js_formatter/src/js/module/export.rs | 10 +- .../src/js/module/export_as_clause.rs | 14 +- .../export_default_declaration_clause.rs | 11 +- .../export_default_expression_clause.rs | 21 +- .../src/js/module/export_from_clause.rs | 33 +- .../src/js/module/export_named_clause.rs | 45 +- .../src/js/module/export_named_from_clause.rs | 82 +- .../js/module/export_named_from_specifier.rs | 29 +- .../export_named_shorthand_specifier.rs | 20 +- .../src/js/module/export_named_specifier.rs | 17 +- .../rome_js_formatter/src/js/module/import.rs | 18 +- .../src/js/module/import_assertion.rs | 24 +- .../src/js/module/import_assertion_entry.rs | 36 +- .../src/js/module/import_bare_clause.rs | 23 +- .../src/js/module/import_default_clause.rs | 29 +- .../src/js/module/import_meta.rs | 10 +- .../src/js/module/import_named_clause.rs | 36 +- .../src/js/module/import_namespace_clause.rs | 29 +- .../src/js/module/literal_export_name.rs | 20 +- .../src/js/module/module_source.rs | 12 +- .../src/js/module/named_import_specifier.rs | 18 +- .../src/js/module/named_import_specifiers.rs | 22 +- .../js/module/namespace_import_specifier.rs | 23 +- .../shorthand_named_import_specifier.rs | 21 +- .../src/js/objects/computed_member_name.rs | 11 +- .../src/js/objects/getter_object_member.rs | 11 +- .../src/js/objects/literal_member_name.rs | 12 +- .../src/js/objects/method_object_member.rs | 18 +- .../js/objects/private_class_member_name.rs | 9 +- .../src/js/objects/property_object_member.rs | 152 +- .../src/js/objects/setter_object_member.rs | 11 +- .../shorthand_property_object_member.rs | 9 +- .../src/js/statements/block_statement.rs | 42 +- .../src/js/statements/break_statement.rs | 34 +- .../src/js/statements/continue_statement.rs | 34 +- .../src/js/statements/debugger_statement.rs | 18 +- .../src/js/statements/do_while_statement.rs | 41 +- .../src/js/statements/empty_statement.rs | 11 +- .../src/js/statements/expression_statement.rs | 18 +- .../src/js/statements/for_in_statement.rs | 44 +- .../src/js/statements/for_of_statement.rs | 50 +- .../src/js/statements/for_statement.rs | 80 +- .../src/js/statements/if_statement.rs | 65 +- .../src/js/statements/labeled_statement.rs | 25 +- .../src/js/statements/return_statement.rs | 66 +- .../src/js/statements/switch_statement.rs | 50 +- .../src/js/statements/throw_statement.rs | 18 +- .../js/statements/try_finally_statement.rs | 29 +- .../src/js/statements/try_statement.rs | 11 +- .../src/js/statements/variable_statement.rs | 18 +- .../src/js/statements/while_statement.rs | 35 +- .../src/js/statements/with_statement.rs | 35 +- .../src/js/unknown/unknown.rs | 5 +- .../src/js/unknown/unknown_assignment.rs | 8 +- .../src/js/unknown/unknown_binding.rs | 8 +- .../src/js/unknown/unknown_expression.rs | 8 +- .../unknown/unknown_import_assertion_entry.rs | 9 +- .../src/js/unknown/unknown_member.rs | 8 +- .../unknown/unknown_named_import_specifier.rs | 9 +- .../src/js/unknown/unknown_parameter.rs | 8 +- .../src/js/unknown/unknown_statement.rs | 8 +- .../src/jsx/any/attribute.rs | 6 +- .../src/jsx/any/attribute_name.rs | 6 +- .../src/jsx/any/attribute_value.rs | 10 +- crates/rome_js_formatter/src/jsx/any/child.rs | 14 +- .../src/jsx/any/element_name.rs | 12 +- crates/rome_js_formatter/src/jsx/any/name.rs | 6 +- .../src/jsx/any/object_name.rs | 10 +- crates/rome_js_formatter/src/jsx/any/tag.rs | 8 +- .../src/jsx/attribute/attribute.rs | 5 +- .../attribute/attribute_initializer_clause.rs | 8 +- .../attribute/expression_attribute_value.rs | 107 +- .../src/jsx/attribute/spread_attribute.rs | 10 +- .../src/jsx/auxiliary/expression_child.rs | 8 +- .../src/jsx/auxiliary/name.rs | 5 +- .../src/jsx/auxiliary/namespace_name.rs | 11 +- .../src/jsx/auxiliary/reference_identifier.rs | 8 +- .../src/jsx/auxiliary/spread_child.rs | 8 +- .../src/jsx/auxiliary/string.rs | 5 +- .../src/jsx/auxiliary/text.rs | 19 +- .../src/jsx/expressions/tag_expression.rs | 8 +- .../src/jsx/lists/attribute_list.rs | 14 +- .../src/jsx/lists/child_list.rs | 5 +- .../src/jsx/objects/member_name.rs | 8 +- .../src/jsx/tag/closing_element.rs | 8 +- .../src/jsx/tag/closing_fragment.rs | 10 +- .../rome_js_formatter/src/jsx/tag/element.rs | 5 +- .../rome_js_formatter/src/jsx/tag/fragment.rs | 7 +- .../src/jsx/tag/opening_element.rs | 8 +- .../src/jsx/tag/opening_fragment.rs | 8 +- .../src/jsx/tag/self_closing_element.rs | 10 +- crates/rome_js_formatter/src/lib.rs | 103 +- crates/rome_js_formatter/src/prelude.rs | 11 +- crates/rome_js_formatter/src/separated.rs | 201 ++ .../any/external_module_declaration_body.rs | 11 +- .../src/ts/any/index_signature_modifier.rs | 13 +- .../src/ts/any/method_signature_modifier.rs | 21 +- .../src/ts/any/module_name.rs | 6 +- .../src/ts/any/module_reference.rs | 8 +- crates/rome_js_formatter/src/ts/any/name.rs | 6 +- .../src/ts/any/property_annotation.rs | 17 +- .../src/ts/any/property_parameter_modifier.rs | 17 +- .../ts/any/property_signature_annotation.rs | 11 +- .../src/ts/any/property_signature_modifier.rs | 29 +- .../src/ts/any/return_type.rs | 8 +- .../src/ts/any/template_element.rs | 8 +- .../rome_js_formatter/src/ts/any/ts_type.rs | 70 +- .../src/ts/any/tuple_type_element.rs | 19 +- .../src/ts/any/type_member.rs | 32 +- .../ts/any/type_predicate_parameter_name.rs | 13 +- .../src/ts/any/variable_annotation.rs | 13 +- .../src/ts/assignments/as_assignment.rs | 10 +- .../non_null_assertion_assignment.rs | 8 +- .../assignments/type_assertion_assignment.rs | 20 +- .../src/ts/auxiliary/abstract_modifier.rs | 8 +- .../ts/auxiliary/accessibility_modifier.rs | 8 +- .../src/ts/auxiliary/asserts_condition.rs | 8 +- .../auxiliary/call_signature_type_member.rs | 18 +- .../construct_signature_type_member.rs | 17 +- .../src/ts/auxiliary/declare_modifier.rs | 8 +- .../src/ts/auxiliary/default_type_clause.rs | 8 +- .../auxiliary/definite_property_annotation.rs | 9 +- .../auxiliary/definite_variable_annotation.rs | 8 +- .../empty_external_module_declaration_body.rs | 9 +- .../src/ts/auxiliary/enum_member.rs | 16 +- .../ts/auxiliary/external_module_reference.rs | 10 +- .../auxiliary/getter_signature_type_member.rs | 16 +- .../src/ts/auxiliary/implements_clause.rs | 34 +- .../auxiliary/index_signature_type_member.rs | 24 +- .../src/ts/auxiliary/mapped_type_as_clause.rs | 16 +- .../mapped_type_optional_modifier_clause.rs | 12 +- .../mapped_type_readonly_modifier_clause.rs | 12 +- .../auxiliary/method_signature_type_member.rs | 15 +- .../src/ts/auxiliary/module_block.rs | 15 +- .../ts/auxiliary/named_tuple_type_element.rs | 10 +- .../auxiliary/optional_property_annotation.rs | 11 +- .../auxiliary/optional_tuple_type_element.rs | 8 +- .../src/ts/auxiliary/override_modifier.rs | 8 +- .../property_signature_type_member.rs | 16 +- .../src/ts/auxiliary/qualified_module_name.rs | 11 +- .../src/ts/auxiliary/qualified_name.rs | 11 +- .../src/ts/auxiliary/readonly_modifier.rs | 8 +- .../ts/auxiliary/rest_tuple_type_element.rs | 8 +- .../ts/auxiliary/return_type_annotation.rs | 11 +- .../auxiliary/setter_signature_type_member.rs | 31 +- .../src/ts/auxiliary/type_annotation.rs | 8 +- .../ts/auxiliary/type_constraint_clause.rs | 8 +- .../src/ts/auxiliary/type_parameter_name.rs | 8 +- .../src/ts/bindings/identifier_binding.rs | 8 +- .../ts/bindings/index_signature_parameter.rs | 8 +- .../src/ts/bindings/property_parameter.rs | 10 +- .../src/ts/bindings/this_parameter.rs | 8 +- .../src/ts/bindings/type_parameter.rs | 29 +- .../src/ts/bindings/type_parameters.rs | 21 +- .../constructor_signature_class_member.rs | 24 +- .../src/ts/classes/extends_clause.rs | 34 +- .../classes/getter_signature_class_member.rs | 24 +- .../classes/index_signature_class_member.rs | 23 +- .../classes/method_signature_class_member.rs | 25 +- .../property_signature_class_member.rs | 24 +- .../classes/setter_signature_class_member.rs | 39 +- .../declare_function_declaration.rs | 34 +- .../src/ts/declarations/enum_declaration.rs | 50 +- .../external_module_declaration.rs | 11 +- .../src/ts/declarations/global_declaration.rs | 12 +- .../declarations/import_equals_declaration.rs | 25 +- .../ts/declarations/interface_declaration.rs | 37 +- .../src/ts/declarations/module_declaration.rs | 10 +- .../ts/declarations/type_alias_declaration.rs | 23 +- .../src/ts/expressions/as_expression.rs | 10 +- .../expressions/name_with_type_arguments.rs | 8 +- .../non_null_assertion_expression.rs | 8 +- .../ts/expressions/template_chunk_element.rs | 5 +- .../src/ts/expressions/template_element.rs | 5 +- .../ts/expressions/template_literal_type.rs | 10 +- .../src/ts/expressions/type_arguments.rs | 17 +- .../expressions/type_assertion_expression.rs | 20 +- .../src/ts/lists/enum_member_list.rs | 16 +- .../ts/lists/index_signature_modifier_list.rs | 13 +- .../lists/intersection_type_element_list.rs | 48 +- .../lists/method_signature_modifier_list.rs | 12 +- .../lists/property_parameter_modifier_list.rs | 12 +- .../lists/property_signature_modifier_list.rs | 12 +- .../src/ts/lists/template_element_list.rs | 18 +- .../src/ts/lists/tuple_type_element_list.rs | 12 +- .../src/ts/lists/type_argument_list.rs | 20 +- .../src/ts/lists/type_list.rs | 20 +- .../src/ts/lists/type_member_list.rs | 81 +- .../src/ts/lists/type_parameter_list.rs | 15 +- .../src/ts/lists/union_type_variant_list.rs | 77 +- .../ts/module/export_as_namespace_clause.rs | 25 +- .../src/ts/module/export_assignment_clause.rs | 21 +- .../src/ts/module/export_declare_clause.rs | 10 +- .../src/ts/module/import_type.rs | 14 +- .../src/ts/module/import_type_qualifier.rs | 8 +- .../src/ts/statements/declare_statement.rs | 10 +- .../src/ts/types/any_type.rs | 5 +- .../src/ts/types/array_type.rs | 7 +- .../src/ts/types/asserts_return_type.rs | 10 +- .../src/ts/types/big_int_literal_type.rs | 8 +- .../src/ts/types/bigint_type.rs | 5 +- .../src/ts/types/boolean_literal_type.rs | 8 +- .../src/ts/types/boolean_type.rs | 5 +- .../src/ts/types/conditional_type.rs | 7 +- .../src/ts/types/constructor_type.rs | 17 +- .../src/ts/types/function_type.rs | 10 +- .../src/ts/types/indexed_access_type.rs | 10 +- .../src/ts/types/infer_type.rs | 10 +- .../src/ts/types/intersection_type.rs | 56 +- .../src/ts/types/mapped_type.rs | 62 +- .../src/ts/types/never_type.rs | 5 +- .../src/ts/types/non_primitive_type.rs | 8 +- .../src/ts/types/null_literal_type.rs | 8 +- .../src/ts/types/number_literal_type.rs | 8 +- .../src/ts/types/number_type.rs | 5 +- .../src/ts/types/object_type.rs | 33 +- .../src/ts/types/parenthesized_type.rs | 21 +- .../src/ts/types/predicate_return_type.rs | 10 +- .../src/ts/types/reference_type.rs | 8 +- .../src/ts/types/string_literal_type.rs | 12 +- .../src/ts/types/string_type.rs | 5 +- .../src/ts/types/symbol_type.rs | 5 +- .../src/ts/types/this_type.rs | 5 +- .../src/ts/types/tuple_type.rs | 18 +- .../src/ts/types/type_operator_type.rs | 16 +- .../src/ts/types/typeof_type.rs | 14 +- .../src/ts/types/undefined_type.rs | 8 +- .../src/ts/types/union_type.rs | 52 +- .../src/ts/types/unknown_type.rs | 6 +- .../src/ts/types/void_type.rs | 5 +- crates/rome_js_formatter/src/utils/array.rs | 80 +- .../src/utils/binary_like_expression.rs | 226 ++- .../src/utils/format_conditional.rs | 226 +-- .../src/utils/member_chain/flatten_item.rs | 18 +- .../src/utils/member_chain/groups.rs | 44 +- .../src/utils/member_chain/mod.rs | 98 +- .../src/utils/member_chain/simple_argument.rs | 4 +- crates/rome_js_formatter/src/utils/mod.rs | 366 ++-- .../src/utils/string_utils.rs | 73 +- crates/rome_rowan/src/ast/mod.rs | 10 +- crates/rome_rowan/src/cursor/trivia.rs | 1 + crates/rome_rowan/src/syntax.rs | 3 +- crates/rome_rowan/src/syntax/trivia.rs | 1 + xtask/codegen/src/formatter.rs | 29 +- 424 files changed, 8482 insertions(+), 8249 deletions(-) create mode 100644 crates/rome_formatter/src/arguments.rs create mode 100644 crates/rome_formatter/src/buffer.rs create mode 100644 crates/rome_js_formatter/src/builders.rs delete mode 100644 crates/rome_js_formatter/src/formatter.rs create mode 100644 crates/rome_js_formatter/src/separated.rs diff --git a/crates/rome_formatter/src/arguments.rs b/crates/rome_formatter/src/arguments.rs new file mode 100644 index 00000000000..ce38a1a5852 --- /dev/null +++ b/crates/rome_formatter/src/arguments.rs @@ -0,0 +1,154 @@ +use super::{Buffer, Format, Formatter}; +use crate::FormatResult; +use std::ffi::c_void; +use std::marker::PhantomData; + +/// Mono-morphed type to format an object. Used by the [rome_formatter::format], [rome_formatter::format_args], and +/// [rome_formatter::write] macros. +/// +/// This struct is similar to a dynamic dispatch (using `dyn Format`) because it stores a pointer to the value. +/// However, it doesn't store the pointer to `dyn Format`'s vtable, instead it statically resolves the function +/// pointer of `Format::format` and stores it in `formatter`. +pub struct Argument<'fmt, Context> { + /// The value to format stored as a raw pointer where `lifetime` stores the value's lifetime. + value: *const c_void, + + /// Stores the lifetime of the value. To get the most out of our dear borrow checker. + lifetime: PhantomData<&'fmt ()>, + + /// The function pointer to `value`'s `Format::format` method + formatter: fn(*const c_void, &mut Formatter<'_, Context>) -> FormatResult<()>, +} + +impl Clone for Argument<'_, Context> { + fn clone(&self) -> Self { + *self + } +} +impl Copy for Argument<'_, Context> {} + +impl<'fmt, Context> Argument<'fmt, Context> { + /// Called by the [rome_formatter::format_args] macro. Creates a mono-morphed value for formatting + /// an object. + #[doc(hidden)] + #[inline] + pub fn new>(value: &'fmt F) -> Self { + fn formatter, Context>( + ptr: *const c_void, + fmt: &mut Formatter, + ) -> FormatResult<()> { + // SAFETY: Safe because the 'fmt lifetime is captured by the 'lifetime' field. + F::fmt(unsafe { &*(ptr as *const F) }, fmt) + } + + Self { + value: value as *const F as *const c_void, + lifetime: PhantomData, + formatter: formatter::, + } + } + + /// Formats the value stored by this argument using the given formatter. + #[inline] + pub(super) fn format(&self, f: &mut Formatter) -> FormatResult<()> { + (self.formatter)(self.value, f) + } +} + +/// Sequence of objects that should be formatted in the specified order. +/// +/// The [`format_args!`] macro will safely create an instance of this structure. +/// +/// You can use the `Arguments` that [`format_args!]` return in `Format` context as seen below. +/// It will call the `format` function for every of it's objects. +/// +/// ```rust +/// use rome_formatter::prelude::*; +/// use rome_formatter::{format, format_args}; +/// +/// let formatted = format!(SimpleFormatContext::default(), [ +/// format_args!(token("a"), space_token(), token("b")) +/// ]).unwrap(); +/// +/// assert_eq!("a b", formatted.print().as_code()); +/// ``` +pub struct Arguments<'fmt, Context>(pub &'fmt [Argument<'fmt, Context>]); + +impl<'fmt, Context> Arguments<'fmt, Context> { + #[doc(hidden)] + #[inline] + pub fn new(arguments: &'fmt [Argument<'fmt, Context>]) -> Self { + Self(arguments) + } + + /// Returns the arguments + #[inline] + pub(super) fn items(&self) -> &'fmt [Argument<'fmt, Context>] { + self.0 + } +} + +impl Copy for Arguments<'_, Context> {} + +impl Clone for Arguments<'_, Context> { + fn clone(&self) -> Self { + Self(self.0) + } +} + +impl Format for Arguments<'_, Context> { + #[inline] + fn fmt(&self, formatter: &mut Formatter) -> FormatResult<()> { + formatter.write_fmt(*self) + } +} + +impl std::fmt::Debug for Arguments<'_, Context> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("Arguments[...]") + } +} + +impl<'fmt, Context> From<&'fmt Argument<'fmt, Context>> for Arguments<'fmt, Context> { + fn from(argument: &'fmt Argument<'fmt, Context>) -> Self { + Arguments::new(std::slice::from_ref(argument)) + } +} + +#[cfg(test)] +mod tests { + use crate::prelude::*; + use crate::{format_args, write, FormatState, VecBuffer}; + + #[test] + fn test_nesting() { + let mut context = FormatState::new(()); + let mut buffer = VecBuffer::new(&mut context); + + write!( + &mut buffer, + [ + token("function"), + space_token(), + token("a"), + space_token(), + group_elements(&format_args!(token("("), token(")"))) + ] + ) + .unwrap(); + + assert_eq!( + buffer.into_element(), + FormatElement::List(List::new(vec![ + FormatElement::Token(Token::Static { text: "function" }), + FormatElement::Space, + FormatElement::Token(Token::Static { text: "a" }), + FormatElement::Space, + FormatElement::Group(Group::new(FormatElement::List(List::new(vec![ + FormatElement::Token(Token::Static { text: "(" }), + FormatElement::Token(Token::Static { text: ")" }), + ])))) + ])) + ); + } +} diff --git a/crates/rome_formatter/src/buffer.rs b/crates/rome_formatter/src/buffer.rs new file mode 100644 index 00000000000..c40d5d989b5 --- /dev/null +++ b/crates/rome_formatter/src/buffer.rs @@ -0,0 +1,438 @@ +use super::{write, Arguments, FormatElement}; +use crate::format_element::List; +use std::any::{Any, TypeId}; + +use crate::{Format, FormatResult, FormatState}; + +use std::fmt::Debug; +use std::ops::{Deref, DerefMut}; + +/// A trait for writing or formatting into [FormatElement]-accepting buffers or streams. +pub trait Buffer { + /// The context used during formatting + type Context; + + /// Writes a [`FormatElement`] into this buffer, returning whether the write succeeded. + /// + /// # Errors + /// This function will return an instance of [`FormatError`] on error. + /// + /// # Examples + /// + /// ``` + /// use rome_formatter::{Buffer, FormatElement, FormatState, SimpleFormatContext, Token, VecBuffer}; + /// + /// let mut state = FormatState::new(SimpleFormatContext::default()); + /// let mut buffer = VecBuffer::new(&mut state); + /// + /// buffer.write_element(FormatElement::Token( Token::Static { text: "test"})).unwrap(); + /// + /// assert_eq!(buffer.into_element(), FormatElement::Token( Token::Static { text: "test"})); + /// ``` + /// + fn write_element(&mut self, element: FormatElement) -> FormatResult<()>; + + /// Glue for usage of the [`write!`] macro with implementors of this trait. + /// + /// This method should generally not be invoked manually, but rather through the [`write!`] macro itself. + /// + /// # Examples + /// + /// ``` + /// use rome_formatter::prelude::*; + /// use rome_formatter::{Buffer, FormatState, SimpleFormatContext, Token, VecBuffer, format_args}; + /// + /// let mut state = FormatState::new(SimpleFormatContext::default()); + /// let mut buffer = VecBuffer::new(&mut state); + /// + /// buffer.write_fmt(format_args!(token("Hello World"))).unwrap(); + /// + /// assert_eq!(buffer.into_element(), FormatElement::Token( Token::Static { text: "Hello World"})); + /// ``` + fn write_fmt(mut self: &mut Self, arguments: Arguments) -> FormatResult<()> { + write(&mut self, arguments) + } + + /// Returns the formatting state relevant for this formatting session. + fn state(&self) -> &FormatState; + + /// Returns the mutable formatting state relevant for this formatting session. + fn state_mut(&mut self) -> &mut FormatState; + + /// Takes a snapshot of the Buffers state, excluding the formatter state. + fn snapshot(&self) -> BufferSnapshot; + + /// Restores the snapshot buffer + /// + /// ## Panics + /// If the passed snapshot id is a snapshot of another buffer OR + /// if the snapshot is restored out of order + fn restore_snapshot(&mut self, snapshot: BufferSnapshot); +} + +/// Snapshot of a buffer state that can be restored at a later point. +/// +/// Used in cases where the formatting of an object fails but a parent formatter knows an alternative +/// strategy on how to format the object that might succeed. +#[derive(Debug)] +pub enum BufferSnapshot { + /// Stores an absolute position of a buffers state, for example, the offset of the last written element. + Position(usize), + + /// Generic structure for custom buffers that need to store more complex data. Slightly more + /// expensive because it requires allocating the buffer state on the heap. + Any(Box), +} + +impl BufferSnapshot { + /// Creates a new buffer snapshot that points to the specified position. + pub const fn position(index: usize) -> Self { + Self::Position(index) + } + + /// Unwraps the position value. + /// + /// # Panics + /// + /// If self is not a [`BufferSnapshot::Position`] + pub fn unwrap_position(&self) -> usize { + match self { + BufferSnapshot::Position(index) => *index, + BufferSnapshot::Any(_) => panic!("Tried to unwrap Any snapshot as a position."), + } + } + + /// Unwraps the any value. + /// + /// # Panics + /// + /// If `self` is not a [`BufferSnapshot::Any`]. + pub fn unwrap_any(self) -> T { + match self { + BufferSnapshot::Position(_) => { + panic!("Tried to unwrap Position snapshot as Any snapshot.") + } + BufferSnapshot::Any(value) => match value.downcast::() { + Ok(snapshot) => *snapshot, + Err(err) => { + panic!( + "Tried to unwrap snapshot of type {:?} as {:?}", + err.type_id(), + TypeId::of::() + ) + } + }, + } + } +} + +/// Implements the `[Buffer]` trait for all mutable references of objects implementing [Buffer]. +impl + ?Sized, Context> Buffer for &mut W { + type Context = Context; + + fn write_element(&mut self, element: FormatElement) -> FormatResult<()> { + (**self).write_element(element) + } + + fn write_fmt(&mut self, args: Arguments) -> FormatResult<()> { + (**self).write_fmt(args) + } + + fn state(&self) -> &FormatState { + (**self).state() + } + + fn state_mut(&mut self) -> &mut FormatState { + (**self).state_mut() + } + + fn snapshot(&self) -> BufferSnapshot { + (**self).snapshot() + } + + fn restore_snapshot(&mut self, snapshot: BufferSnapshot) { + (**self).restore_snapshot(snapshot) + } +} + +/// Vector backed [`Buffer`] implementation. +/// +/// The buffer writes all elements into the internal elements buffer. +#[derive(Debug)] +pub struct VecBuffer<'a, Context> { + state: &'a mut FormatState, + elements: Vec, +} + +impl<'a, Context> VecBuffer<'a, Context> { + pub fn new(state: &'a mut FormatState) -> Self { + Self { + state, + elements: vec![], + } + } + + /// Creates a buffer with the specified capacity + pub fn with_capacity(capacity: usize, context: &'a mut FormatState) -> Self { + Self { + state: context, + elements: Vec::with_capacity(capacity), + } + } + + /// Consumes the buffer and returns its content as a [`FormatElement`] + pub fn into_element(mut self) -> FormatElement { + self.take() + } + + /// Consumes the buffer and returns the written [`FormatElement]`s as a vector. + pub fn into_vec(self) -> Vec { + self.elements + } + + /// Takes the elements without consuming self + pub fn take(&mut self) -> FormatElement { + if self.len() == 1 { + // Safety: Guaranteed by len check above + self.elements.pop().unwrap() + } else { + FormatElement::List(List::new(std::mem::take(&mut self.elements))) + } + } +} + +impl Deref for VecBuffer<'_, Context> { + type Target = [FormatElement]; + + fn deref(&self) -> &Self::Target { + &self.elements + } +} + +impl DerefMut for VecBuffer<'_, Context> { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.elements + } +} + +impl Buffer for VecBuffer<'_, Context> { + type Context = Context; + + fn write_element(&mut self, element: FormatElement) -> FormatResult<()> { + match element { + FormatElement::List(list) => { + if self.elements.is_empty() { + self.elements = list.into_vec() + } else { + self.elements.extend(list.into_vec()) + } + } + element => self.elements.push(element), + } + + Ok(()) + } + + fn state(&self) -> &FormatState { + self.state + } + + fn state_mut(&mut self) -> &mut FormatState { + &mut self.state + } + + fn snapshot(&self) -> BufferSnapshot { + BufferSnapshot::position(self.elements.len()) + } + + fn restore_snapshot(&mut self, snapshot: BufferSnapshot) { + let position = snapshot.unwrap_position(); + assert!( + self.elements.len() >= position, + r#"Outdated snapshot. This buffer contains fewer elements than at the time the snapshot was taken. +Make sure that you take and restore the snapshot in order and that this snapshot belongs to the current buffer."# + ); + + self.elements.truncate(position); + } +} + +/// This struct wraps an existing buffer and emits a preamble text when the first text is written. +/// +/// This can be useful if you, for example, want to write some content if what gets written next isn't empty. +/// +/// # Examples +/// +/// ``` +/// use rome_formatter::{FormatState, Formatted, PreambleBuffer, SimpleFormatContext, VecBuffer, write}; +/// use rome_formatter::prelude::*; +/// +/// let mut state = FormatState::new(SimpleFormatContext::default()); +/// let mut buffer = VecBuffer::new(&mut state); +/// +/// struct Preamble; +/// +/// impl Format for Preamble { +/// fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { +/// write!(f, [token("# heading"), hard_line_break()]) +/// } +/// } +/// +/// let mut with_preamble = PreambleBuffer::new(&mut buffer, Preamble); +/// +/// write!(&mut with_preamble, [token("this text will be on a new line")]).unwrap(); +/// +/// drop(with_preamble); +/// +/// let formatted = Formatted::new(buffer.into_element(), PrinterOptions::default()); +/// assert_eq!("# heading\nthis text will be on a new line", formatted.print().as_code()); +/// ``` +/// +/// The pre-amble does not get written if no content is written to the buffer. +/// +/// ``` +/// use rome_formatter::{FormatState, Formatted, PreambleBuffer, SimpleFormatContext, VecBuffer, write}; +/// use rome_formatter::prelude::*; +/// +/// let mut state = FormatState::new(SimpleFormatContext::default()); +/// let mut buffer = VecBuffer::new(&mut state); +/// +/// struct Preamble; +/// +/// impl Format for Preamble { +/// fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { +/// write!(f, [token("# heading"), hard_line_break()]) +/// } +/// } +/// +/// let mut with_preamble = PreambleBuffer::new(&mut buffer, Preamble); +/// drop(with_preamble); +/// +/// let formatted = Formatted::new(buffer.into_element(), PrinterOptions::default()); +/// assert_eq!("", formatted.print().as_code()); +/// ``` +pub struct PreambleBuffer<'buf, Preamble, Context> { + /// The wrapped buffer + inner: &'buf mut dyn Buffer, + + /// The pre-amble to write once the first content gets written to this buffer. + preamble: Preamble, + + /// Whether some content (including the pre-amble) has been written at this point. + empty: bool, +} + +impl<'buf, Preamble, Context> PreambleBuffer<'buf, Preamble, Context> { + pub fn new(inner: &'buf mut dyn Buffer, preamble: Preamble) -> Self { + Self { + inner, + preamble, + empty: true, + } + } + + /// Returns `true` if the preamble has been written, `false` otherwise. + pub fn did_write_preamble(&self) -> bool { + !self.empty + } +} + +impl Buffer for PreambleBuffer<'_, Preamble, Context> +where + Preamble: Format, +{ + type Context = Context; + + fn write_element(&mut self, element: FormatElement) -> FormatResult<()> { + if element.is_empty() { + Ok(()) + } else { + if self.empty { + write!(self.inner, [&self.preamble])?; + self.empty = false; + } + + self.inner.write_element(element) + } + } + + fn state(&self) -> &FormatState { + self.inner.state() + } + + fn state_mut(&mut self) -> &mut FormatState { + self.inner.state_mut() + } + + fn snapshot(&self) -> BufferSnapshot { + BufferSnapshot::Any(Box::new(PreambleBufferSnapshot { + inner: self.inner.snapshot(), + empty: self.empty, + })) + } + + fn restore_snapshot(&mut self, snapshot: BufferSnapshot) { + let snapshot = snapshot.unwrap_any::(); + + self.empty = snapshot.empty; + self.inner.restore_snapshot(snapshot.inner); + } +} + +struct PreambleBufferSnapshot { + inner: BufferSnapshot, + empty: bool, +} + +/// Buffer that allows you inspecting elements as they get written to the formatter. +pub struct Inspect<'inner, Context, Inspector> { + inner: &'inner mut dyn Buffer, + inspector: Inspector, +} + +impl<'inner, Context, Inspector> Inspect<'inner, Context, Inspector> { + pub fn new(inner: &'inner mut dyn Buffer, inspector: Inspector) -> Self { + Self { inner, inspector } + } +} + +impl<'inner, Context, Inspector> Buffer for Inspect<'inner, Context, Inspector> +where + Inspector: FnMut(&FormatElement), +{ + type Context = Context; + + fn write_element(&mut self, element: FormatElement) -> FormatResult<()> { + (self.inspector)(&element); + self.inner.write_element(element) + } + + fn state(&self) -> &FormatState { + self.inner.state() + } + + fn state_mut(&mut self) -> &mut FormatState { + self.inner.state_mut() + } + + fn snapshot(&self) -> BufferSnapshot { + self.inner.snapshot() + } + + fn restore_snapshot(&mut self, snapshot: BufferSnapshot) { + self.inner.restore_snapshot(snapshot) + } +} + +pub trait BufferExtensions: Buffer + Sized { + /// Returns a new buffer that calls the passed inspector for every element that gets written to the output + #[must_use] + fn inspect(&mut self, inspector: F) -> Inspect + where + F: FnMut(&FormatElement), + { + Inspect::new(self, inspector) + } +} + +impl BufferExtensions for T where T: Buffer {} diff --git a/crates/rome_formatter/src/builders.rs b/crates/rome_formatter/src/builders.rs index ee65ebe4cca..bb86873e973 100644 --- a/crates/rome_formatter/src/builders.rs +++ b/crates/rome_formatter/src/builders.rs @@ -1,69 +1,1730 @@ use crate::prelude::*; +use crate::{ + format_element, write, Argument, Arguments, GroupId, PreambleBuffer, TextRange, TextSize, +}; +use crate::{Buffer, VecBuffer}; +use rome_rowan::{Language, SyntaxNode, SyntaxToken, SyntaxTokenText, TextLen}; +use std::borrow::Cow; +use std::cell::Cell; +use std::marker::PhantomData; -#[derive(Default)] -pub struct ConcatBuilder { - elements: Vec, - size_hint: Option, +/// A no-op element. +/// +/// Doesn't write any content. Useful in combination with `format_replaced` to remove a token but +/// still format its comments. +pub const fn empty_element() -> Empty { + Empty } -impl ConcatBuilder { - #[inline] - pub fn new() -> Self { - Self { - elements: vec![], - size_hint: None, +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub struct Empty; + +impl Format for Empty { + fn fmt(&self, _: &mut Formatter) -> FormatResult<()> { + Ok(()) + } +} + +/// A line break that only gets printed if the enclosing `Group` doesn't fit on a single line. +/// It's omitted if the enclosing `Group` fits on a single line. +/// A soft line break is identical to a hard line break when not enclosed inside of a `Group`. +/// +/// # Examples +/// +/// Soft line breaks are omitted if the enclosing `Group` fits on a single line +/// +/// ``` +/// use rome_formatter::{format, format_args}; +/// use rome_formatter::prelude::*; +/// +/// let elements = format!(SimpleFormatContext::default(), [ +/// group_elements(&format_args![token("a,"), soft_line_break(), token("b")]) +/// ]).unwrap(); +/// +/// assert_eq!( +/// "a,b", +/// elements.print().as_code() +/// ); +/// ``` +/// See [soft_line_break_or_space] if you want to insert a space between the elements if the enclosing +/// `Group` fits on a single line. +/// +/// Soft line breaks are emitted if the enclosing `Group` doesn't fit on a single line +/// ``` +/// use rome_formatter::{format, format_args, LineWidth}; +/// use rome_formatter::prelude::*; +/// +/// let context = SimpleFormatContext { +/// line_width: LineWidth::try_from(10).unwrap(), +/// ..SimpleFormatContext::default() +/// }; +/// +/// let elements = format!(context, [ +/// group_elements(&format_args![ +/// token("a long word,"), +/// soft_line_break(), +/// token("so that the group doesn't fit on a single line"), +/// ]) +/// ]).unwrap(); +/// +/// assert_eq!( +/// "a long word,\nso that the group doesn't fit on a single line", +/// elements.print().as_code() +/// ); +/// ``` +#[inline] +pub const fn soft_line_break() -> Line { + Line::new(LineMode::Soft) +} + +/// A forced line break that are always printed. A hard line break forces any enclosing `Group` +/// to be printed over multiple lines. +/// +/// # Examples +/// +/// It forces a line break, even if the enclosing `Group` would otherwise fit on a single line. +/// ``` +/// use rome_formatter::{format, format_args}; +/// use rome_formatter::prelude::*; +/// +/// let elements = format!(SimpleFormatContext::default(), [ +/// group_elements(&format_args![ +/// token("a,"), +/// hard_line_break(), +/// token("b"), +/// hard_line_break() +/// ]) +/// ]).unwrap(); +/// +/// assert_eq!( +/// "a,\nb\n", +/// elements.print().as_code() +/// ); +/// ``` +#[inline] +pub const fn hard_line_break() -> Line { + Line::new(LineMode::Hard) +} + +/// A forced empty line. An empty line inserts enough line breaks in the output for +/// the previous and next element to be separated by an empty line. +/// +/// # Examples +/// +/// ``` +/// use rome_formatter::{format, format_args}; +/// use rome_formatter::prelude::*; +/// +/// let elements = format!( +/// SimpleFormatContext::default(), [ +/// group_elements(&format_args![ +/// token("a,"), +/// empty_line(), +/// token("b"), +/// empty_line() +/// ]) +/// ]).unwrap(); +/// +/// assert_eq!( +/// "a,\n\nb\n\n", +/// elements.print().as_code() +/// ); +/// ``` +#[inline] +pub const fn empty_line() -> Line { + Line::new(LineMode::Empty) +} + +/// A line break if the enclosing `Group` doesn't fit on a single line, a space otherwise. +/// +/// # Examples +/// +/// The line breaks are emitted as spaces if the enclosing `Group` fits on a a single line: +/// ``` +/// use rome_formatter::{format, format_args}; +/// use rome_formatter::prelude::*; +/// +/// let elements = format!(SimpleFormatContext::default(), [ +/// group_elements(&format_args![ +/// token("a,"), +/// soft_line_break_or_space(), +/// token("b"), +/// ]) +/// ]).unwrap(); +/// +/// assert_eq!( +/// "a, b", +/// elements.print().as_code() +/// ); +/// ``` +/// +/// The printer breaks the lines if the enclosing `Group` doesn't fit on a single line: +/// ``` +/// use rome_formatter::{format_args, format, LineWidth}; +/// use rome_formatter::prelude::*; +/// +/// let context = SimpleFormatContext { +/// line_width: LineWidth::try_from(10).unwrap(), +/// ..SimpleFormatContext::default() +/// }; +/// +/// let elements = format!(context, [ +/// group_elements(&format_args![ +/// token("a long word,"), +/// soft_line_break_or_space(), +/// token("so that the group doesn't fit on a single line"), +/// ]) +/// ]).unwrap(); +/// +/// assert_eq!( +/// "a long word,\nso that the group doesn't fit on a single line", +/// elements.print().as_code() +/// ); +/// ``` +#[inline] +pub const fn soft_line_break_or_space() -> Line { + Line::new(LineMode::SoftOrSpace) +} + +#[derive(Copy, Clone, Eq, PartialEq)] +pub struct Line { + mode: LineMode, +} + +impl Line { + const fn new(mode: LineMode) -> Self { + Self { mode } + } +} + +impl Format for Line { + fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { + f.write_element(FormatElement::Line(self.mode)) + } +} + +impl std::fmt::Debug for Line { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_tuple("Line").field(&self.mode).finish() + } +} + +/// Creates a token that gets written as is to the output. Make sure to properly escape the text if +/// it's user generated (e.g. a string and not a language keyword). +/// +/// # Line feeds +/// Tokens may contain line breaks but they must use the line feeds (`\n`). +/// The [crate::Printer] converts the line feed characters to the character specified in the [crate::PrinterOptions]. +/// +/// # Examples +/// +/// ``` +/// use rome_formatter::format; +/// use rome_formatter::prelude::*; +/// +/// let elements = format!(SimpleFormatContext::default(), [token("Hello World")]).unwrap(); +/// +/// assert_eq!( +/// "Hello World", +/// elements.print().as_code() +/// ); +/// ``` +/// +/// Printing a string literal as a literal requires that the string literal is properly escaped and +/// enclosed in quotes (depending on the target language). +/// +/// ``` +/// use rome_formatter::format; +/// use rome_formatter::prelude::*; +/// +/// // the tab must be encoded as \\t to not literally print a tab character ("Hello{tab}World" vs "Hello\tWorld") +/// let elements = format!(SimpleFormatContext::default(), [token("\"Hello\\tWorld\"")]).unwrap(); +/// +/// assert_eq!(r#""Hello\tWorld""#, elements.print().as_code()); +/// ``` +#[inline] +pub fn token(text: &'static str) -> StaticToken { + debug_assert_no_newlines(text); + + StaticToken { text } +} + +#[derive(Clone, Copy, Eq, PartialEq)] +pub struct StaticToken { + text: &'static str, +} + +impl Format for StaticToken { + fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { + f.write_element(FormatElement::Token(Token::Static { text: self.text })) + } +} + +impl std::fmt::Debug for StaticToken { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + std::write!(f, "StaticToken({})", self.text) + } +} + +/// Create a token from a dynamic string and a range of the input source +pub fn dynamic_token(text: &str, position: TextSize) -> DynamicToken { + debug_assert_no_newlines(text); + + DynamicToken { text, position } +} + +#[derive(Eq, PartialEq)] +pub struct DynamicToken<'a> { + text: &'a str, + position: TextSize, +} + +impl Format for DynamicToken<'_> { + fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { + f.write_element(FormatElement::Token(Token::Dynamic { + text: self.text.to_string().into_boxed_str(), + source_position: self.position, + })) + } +} + +impl std::fmt::Debug for DynamicToken<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + std::write!(f, "DynamicToken({})", self.text) + } +} + +/// String that is the same as in the input source text if `text` is [`Cow::Borrowed`] or +/// some replaced content if `text` is [`Cow::Owned`]. +pub fn syntax_token_cow_slice<'a, L: Language>( + text: Cow<'a, str>, + token: &'a SyntaxToken, + start: TextSize, +) -> SyntaxTokenCowSlice<'a, L> { + debug_assert_no_newlines(&text); + + SyntaxTokenCowSlice { text, token, start } +} + +pub struct SyntaxTokenCowSlice<'a, L: Language> { + text: Cow<'a, str>, + token: &'a SyntaxToken, + start: TextSize, +} + +impl Format for SyntaxTokenCowSlice<'_, L> { + fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { + match &self.text { + Cow::Borrowed(text) => { + let range = TextRange::at(self.start, text.text_len()); + debug_assert_eq!( + *text, + &self.token.text()[range - self.token.text_range().start()], + "The borrowed string doesn't match the specified token substring. Does the borrowed string belong to this token and range?" + ); + + let relative_range = range - self.token.text_range().start(); + let slice = self.token.token_text().slice(relative_range); + + f.write_element(FormatElement::Token(Token::SyntaxTokenSlice { + slice, + source_position: self.start, + })) + } + Cow::Owned(text) => f.write_element(FormatElement::Token(Token::Dynamic { + text: text.to_string().into_boxed_str(), + source_position: self.start, + })), + } + } +} + +impl std::fmt::Debug for SyntaxTokenCowSlice<'_, L> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + std::write!(f, "SyntaxTokenCowSlice({})", self.text) + } +} + +/// Copies a source text 1:1 into the output text. +pub fn syntax_token_text_slice( + token: &SyntaxToken, + range: TextRange, +) -> SyntaxTokenTextSlice { + let relative_range = range - token.text_range().start(); + let slice = token.token_text().slice(relative_range); + + debug_assert_no_newlines(&slice); + + SyntaxTokenTextSlice { + text: slice, + source_position: range.start(), + } +} + +pub struct SyntaxTokenTextSlice { + text: SyntaxTokenText, + source_position: TextSize, +} + +impl Format for SyntaxTokenTextSlice { + fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { + f.write_element(FormatElement::Token(Token::SyntaxTokenSlice { + slice: self.text.clone(), + source_position: self.source_position, + })) + } +} + +impl std::fmt::Debug for SyntaxTokenTextSlice { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + std::write!(f, "SyntaxTokenTextSlice({})", self.text) + } +} + +fn debug_assert_no_newlines(text: &str) { + debug_assert!(!text.contains('\r'), "The content '{}' contains an unsupported '\\r' line terminator character but string tokens must only use line feeds '\\n' as line separator. Use '\\n' instead of '\\r' and '\\r\\n' to insert a line break in strings.", text); +} + +/// Pushes some content to the end of the current line +/// +/// ## Examples +/// +/// ``` +/// use rome_formatter::{format}; +/// use rome_formatter::prelude::*; +/// +/// let elements = format!(SimpleFormatContext::default(), [ +/// token("a"), +/// line_suffix(&token("c")), +/// token("b") +/// ]).unwrap(); +/// +/// assert_eq!( +/// "abc", +/// elements.print().as_code() +/// ); +/// ``` +#[inline] +pub fn line_suffix(inner: &Content) -> LineSuffix +where + Content: Format, +{ + LineSuffix { + content: Argument::new(inner), + } +} + +#[derive(Copy, Clone)] +pub struct LineSuffix<'a, Context> { + content: Argument<'a, Context>, +} + +impl Format for LineSuffix<'_, Context> { + fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { + let mut buffer = VecBuffer::new(f.state_mut()); + buffer.write_fmt(Arguments::from(&self.content))?; + + let content = buffer.into_element(); + f.write_element(FormatElement::LineSuffix(Box::new(content))) + } +} + +impl std::fmt::Debug for LineSuffix<'_, Context> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_tuple("LineSuffix").field(&"{{content}}").finish() + } +} + +/// Inserts a boundary for line suffixes that forces the printer to print all pending line suffixes. +/// Helpful if a line sufix shouldn't pass a certain point. +/// +/// ## Examples +/// +/// Forces the line suffix "c" to be printed before the token `d`. +/// ``` +/// use rome_formatter::format; +/// use rome_formatter::prelude::*; +/// +/// let elements = format!(SimpleFormatContext::default(), [ +/// token("a"), +/// line_suffix(&token("c")), +/// token("b"), +/// line_suffix_boundary(), +/// token("d") +/// ]).unwrap(); +/// +/// assert_eq!( +/// "abc\nd", +/// elements.print().as_code() +/// ); +/// ``` +pub const fn line_suffix_boundary() -> LineSuffixBoundary { + LineSuffixBoundary +} + +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub struct LineSuffixBoundary; + +impl Format for LineSuffixBoundary { + fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { + f.write_element(FormatElement::LineSuffixBoundary) + } +} + +/// Marks some content as a comment trivia. +/// +/// This does not directly influence how this content will be printed, but some +/// parts of the formatter may chose to handle this element in a specific way +/// +/// ## Examples +/// +/// ``` +/// use rome_formatter::{format, format_args}; +/// use rome_formatter::prelude::*; +/// +/// let elements = format!( +/// SimpleFormatContext::default(), +/// [ +/// group_elements(&format_args![ +/// comment(&empty_line()), +/// token("a"), +/// soft_line_break_or_space(), +/// token("b") +/// ]) +/// ] +/// ).unwrap(); +/// +/// assert_eq!( +/// "\na b", +/// elements.print().as_code() +/// ); +/// ``` +#[inline] +pub fn comment(content: &Content) -> Comment +where + Content: Format, +{ + Comment { + content: Argument::new(content), + } +} + +#[derive(Copy, Clone)] +pub struct Comment<'a, Context> { + content: Argument<'a, Context>, +} + +impl Format for Comment<'_, Context> { + fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { + let mut buffer = VecBuffer::new(f.state_mut()); + + buffer.write_fmt(Arguments::from(&self.content))?; + let content = buffer.into_element(); + + f.write_element(FormatElement::Comment(Box::new(content))) + } +} + +impl std::fmt::Debug for Comment<'_, Context> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_tuple("Comment").field(&"{{content}}").finish() + } +} + +/// Inserts a single space. Allows to separate different tokens. +/// +/// # Examples +/// +/// ``` +/// use rome_formatter::format; +/// use rome_formatter::prelude::*; +/// +/// // the tab must be encoded as \\t to not literally print a tab character ("Hello{tab}World" vs "Hello\tWorld") +/// let elements = format!(SimpleFormatContext::default(), [token("a"), space_token(), token("b")]).unwrap(); +/// +/// assert_eq!("a b", elements.print().as_code()); +/// ``` +#[inline] +pub const fn space_token() -> Space { + Space +} + +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub struct Space; + +impl Format for Space { + fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { + f.write_element(FormatElement::Space) + } +} + +/// It adds a level of indentation to the given content +/// +/// It doesn't add any line breaks at the edges of the content, meaning that +/// the line breaks have to be manually added. +/// +/// This helper should be used only in rare cases, instead you should rely more on +/// [block_indent] and [soft_block_indent] +/// +/// # Examples +/// +/// ``` +/// use rome_formatter::{format, format_args}; +/// use rome_formatter::prelude::*; +/// +/// let block = format!(SimpleFormatContext::default(), [ +/// token("switch {"), +/// block_indent(&format_args![ +/// token("default:"), +/// indent(&format_args![ +/// // this is where we want to use a +/// hard_line_break(), +/// token("break;"), +/// ]) +/// ]), +/// token("}"), +/// ]).unwrap(); +/// +/// assert_eq!( +/// "switch {\n\tdefault:\n\t\tbreak;\n}", +/// block.print().as_code() +/// ); +/// ``` +#[inline] +pub fn indent(content: &Content) -> Indent +where + Content: Format, +{ + Indent { + content: Argument::new(content), + } +} + +#[derive(Copy, Clone)] +pub struct Indent<'a, Context> { + content: Argument<'a, Context>, +} + +impl Format for Indent<'_, Context> { + fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { + let mut buffer = VecBuffer::new(f.state_mut()); + + buffer.write_fmt(Arguments::from(&self.content))?; + + if buffer.is_empty() { + return Ok(()); + } + + let content = buffer.into_element(); + f.write_element(FormatElement::Indent(Box::new(content))) + } +} + +impl std::fmt::Debug for Indent<'_, Context> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_tuple("Indent").field(&"{{content}}").finish() + } +} + +/// Inserts a hard line break before and after the content and increases the indention level for the content by one. +/// +/// Block indents indent a block of code, such as in a function body, and therefore insert a line +/// break before and after the content. +/// +/// Doesn't create an indention if the passed in content is [FormatElement.is_empty]. +/// +/// # Examples +/// +/// ``` +/// use rome_formatter::{format, format_args}; +/// use rome_formatter::prelude::*; +/// +/// let block = format![ +/// SimpleFormatContext::default(), +/// [ +/// token("{"), +/// block_indent(&format_args![ +/// token("let a = 10;"), +/// hard_line_break(), +/// token("let c = a + 5;"), +/// ]), +/// token("}"), +/// ] +/// ].unwrap(); +/// +/// assert_eq!( +/// "{\n\tlet a = 10;\n\tlet c = a + 5;\n}", +/// block.print().as_code() +/// ); +/// ``` +#[inline] +pub fn block_indent(content: &impl Format) -> BlockIndent { + BlockIndent { + content: Argument::new(content), + mode: IndentMode::Block, + } +} + +/// Indents the content by inserting a line break before and after the content and increasing +/// the indention level for the content by one if the enclosing group doesn't fit on a single line. +/// Doesn't change the formatting if the enclosing group fits on a single line. +/// +/// # Examples +/// +/// Indents the content by one level and puts in new lines if the enclosing `Group` doesn't fit on a single line +/// +/// ``` +/// use rome_formatter::{format, format_args, LineWidth}; +/// use rome_formatter::prelude::*; +/// +/// let context = SimpleFormatContext { +/// line_width: LineWidth::try_from(10).unwrap(), +/// ..SimpleFormatContext::default() +/// }; +/// +/// let elements = format!(context, [ +/// group_elements(&format_args![ +/// token("["), +/// soft_block_indent(&format_args![ +/// token("'First string',"), +/// soft_line_break_or_space(), +/// token("'second string',"), +/// ]), +/// token("]"), +/// ]) +/// ]).unwrap(); +/// +/// assert_eq!( +/// "[\n\t'First string',\n\t'second string',\n]", +/// elements.print().as_code() +/// ); +/// ``` +/// +/// Doesn't change the formatting if the enclosing `Group` fits on a single line +/// ``` +/// use rome_formatter::{format, format_args}; +/// use rome_formatter::prelude::*; +/// +/// let elements = format!(SimpleFormatContext::default(), [ +/// group_elements(&format_args![ +/// token("["), +/// soft_block_indent(&format_args![ +/// token("5,"), +/// soft_line_break_or_space(), +/// token("10"), +/// ]), +/// token("]"), +/// ]) +/// ]).unwrap(); +/// +/// assert_eq!( +/// "[5, 10]", +/// elements.print().as_code() +/// ); +/// ``` +#[inline] +pub fn soft_block_indent(content: &impl Format) -> BlockIndent { + BlockIndent { + content: Argument::new(content), + mode: IndentMode::Soft, + } +} + +/// If the enclosing `Group` doesn't fit on a single line, inserts a line break and indent. +/// Otherwise, just inserts a space. +/// +/// Line indents are used to break a single line of code, and therefore only insert a line +/// break before the content and not after the content. +/// +/// # Examples +/// +/// Indents the content by one level and puts in new lines if the enclosing `Group` doesn't +/// fit on a single line. Otherwise, just inserts a space. +/// +/// ``` +/// use rome_formatter::{format, format_args, LineWidth}; +/// use rome_formatter::prelude::*; +/// +/// let context = SimpleFormatContext { +/// line_width: LineWidth::try_from(10).unwrap(), +/// ..SimpleFormatContext::default() +/// }; +/// +/// let elements = format!(context, [ +/// group_elements(&format_args![ +/// token("name"), +/// space_token(), +/// token("="), +/// soft_line_indent_or_space(&format_args![ +/// token("firstName"), +/// space_token(), +/// token("+"), +/// space_token(), +/// token("lastName"), +/// ]), +/// ]) +/// ]).unwrap(); +/// +/// assert_eq!( +/// "name =\n\tfirstName + lastName", +/// elements.print().as_code() +/// ); +/// ``` +/// +/// Only adds a space if the enclosing `Group` fits on a single line +/// ``` +/// use rome_formatter::{format, format_args}; +/// use rome_formatter::prelude::*; +/// +/// let elements = format!(SimpleFormatContext::default(), [ +/// group_elements(&format_args![ +/// token("a"), +/// space_token(), +/// token("="), +/// soft_line_indent_or_space(&token("10")), +/// ]) +/// ]).unwrap(); +/// +/// assert_eq!( +/// "a = 10", +/// elements.print().as_code() +/// ); +/// ``` +#[inline] +pub fn soft_line_indent_or_space(content: &impl Format) -> BlockIndent { + BlockIndent { + content: Argument::new(content), + mode: IndentMode::SoftLineOrSpace, + } +} + +#[derive(Copy, Clone)] +pub struct BlockIndent<'a, Context> { + content: Argument<'a, Context>, + mode: IndentMode, +} + +#[derive(Copy, Clone, Eq, PartialEq, Debug)] +enum IndentMode { + Soft, + Block, + SoftLineOrSpace, +} + +impl Format for BlockIndent<'_, Context> { + fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { + let mut buffer = VecBuffer::new(f.state_mut()); + + match self.mode { + IndentMode::Soft => write!(buffer, [soft_line_break()])?, + IndentMode::Block => write!(buffer, [hard_line_break()])?, + IndentMode::SoftLineOrSpace => write!(buffer, [soft_line_break_or_space()])?, + }; + + buffer.write_fmt(Arguments::from(&self.content))?; + + // Don't create an indent if the content is empty + if buffer.len() == 1 { + return Ok(()); } + + let content = buffer.into_element(); + + f.write_element(FormatElement::Indent(Box::new(content)))?; + + match self.mode { + IndentMode::Soft => write!(f, [soft_line_break()])?, + IndentMode::Block => write!(f, [hard_line_break()])?, + IndentMode::SoftLineOrSpace => {} + } + + Ok(()) } +} + +impl std::fmt::Debug for BlockIndent<'_, Context> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let name = match self.mode { + IndentMode::Soft => "SoftBlockIndent", + IndentMode::Block => "HardBlockIndent", + IndentMode::SoftLineOrSpace => "SoftLineIndentOrSpace", + }; + f.debug_tuple(name).field(&"{{content}}").finish() + } +} + +/// Creates a logical `Group` around the content that should either consistently be printed on a single line +/// or broken across multiple lines. +/// +/// The printer will try to print the content of the `Group` on a single line, ignoring all soft line breaks and +/// emitting spaces for soft line breaks or spaces. The printer tracks back if it isn't successful either +/// because it encountered a hard line break, or because printing the `Group` on a single line exceeds +/// the configured line width, and thus it must print all its content on multiple lines, +/// emitting line breaks for all line break kinds. +/// +/// # Examples +/// +/// `Group` that fits on a single line +/// +/// ``` +/// use rome_formatter::{format, format_args}; +/// use rome_formatter::prelude::*; +/// +/// let elements = format!(SimpleFormatContext::default(), [ +/// group_elements(&format_args![ +/// token("["), +/// soft_block_indent(&format_args![ +/// token("1,"), +/// soft_line_break_or_space(), +/// token("2,"), +/// soft_line_break_or_space(), +/// token("3"), +/// ]), +/// token("]"), +/// ]) +/// ]).unwrap(); +/// +/// assert_eq!( +/// "[1, 2, 3]", +/// elements.print().as_code() +/// ); +/// ``` +/// +/// The printer breaks the `Group` over multiple lines if its content doesn't fit on a single line +/// ``` +/// use rome_formatter::{format, format_args, LineWidth}; +/// use rome_formatter::prelude::*; +/// +/// let context = SimpleFormatContext { +/// line_width: LineWidth::try_from(20).unwrap(), +/// ..SimpleFormatContext::default() +/// }; +/// +/// let elements = format!(context, [ +/// group_elements(&format_args![ +/// token("["), +/// soft_block_indent(&format_args![ +/// token("'Good morning! How are you today?',"), +/// soft_line_break_or_space(), +/// token("2,"), +/// soft_line_break_or_space(), +/// token("3"), +/// ]), +/// token("]"), +/// ]) +/// ]).unwrap(); +/// +/// assert_eq!( +/// "[\n\t'Good morning! How are you today?',\n\t2,\n\t3\n]", +/// elements.print().as_code() +/// ); +/// ``` +#[inline] +pub fn group_elements(content: &impl Format) -> GroupElements { + GroupElements { + content: Argument::new(content), + group_id: None, + } +} + +#[derive(Copy, Clone)] +pub struct GroupElements<'a, Context> { + content: Argument<'a, Context>, + group_id: Option, +} + +impl GroupElements<'_, Context> { + pub fn with_group_id(mut self, group_id: Option) -> Self { + self.group_id = group_id; + self + } +} + +impl Format for GroupElements<'_, Context> { + fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { + let mut buffer = VecBuffer::new(f.state_mut()); + + buffer.write_fmt(Arguments::from(&self.content))?; + + let content = buffer.into_element(); + + let (leading, content, trailing) = content.split_trivia(); + let group = Group::new(content).with_id(self.group_id); + + if !leading.is_empty() { + f.write_element(leading)?; + } + f.write_element(FormatElement::Group(group))?; + + if !trailing.is_empty() { + f.write_element(trailing)?; + } + + Ok(()) + } +} + +impl std::fmt::Debug for GroupElements<'_, Context> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("GroupElements") + .field("group_id", &self.group_id) + .field("content", &"{{content}}") + .finish() + } +} + +/// IR element that forces the parent group to print in expanded mode. +/// +/// Has no effect if used outside of a group or element that introduce implicit groups (fill element). +/// +/// ## Examples +/// +/// ``` +/// use rome_formatter::{format, format_args, LineWidth}; +/// use rome_formatter::prelude::*; +/// +/// let elements = format!(SimpleFormatContext::default(), [ +/// group_elements(&format_args![ +/// token("["), +/// soft_block_indent(&format_args![ +/// token("'Good morning! How are you today?',"), +/// soft_line_break_or_space(), +/// token("2,"), +/// expand_parent(), // Forces the parent to expand +/// soft_line_break_or_space(), +/// token("3"), +/// ]), +/// token("]"), +/// ]) +/// ]).unwrap(); +/// +/// assert_eq!( +/// "[\n\t'Good morning! How are you today?',\n\t2,\n\t3\n]", +/// elements.print().as_code() +/// ); +/// ``` +/// +/// # Prettier +/// Equivalent to Prettier's `break_parent` IR element +pub const fn expand_parent() -> ExpandParent { + ExpandParent +} + +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub struct ExpandParent; + +impl Format for ExpandParent { + fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { + f.write_element(FormatElement::ExpandParent) + } +} + +/// Adds a conditional content that is emitted only if it isn't inside an enclosing `Group` that +/// is printed on a single line. The element allows, for example, to insert a trailing comma after the last +/// array element only if the array doesn't fit on a single line. +/// +/// The element has no special meaning if used outside of a `Group`. In that case, the content is always emitted. +/// +/// If you're looking for a way to only print something if the `Group` fits on a single line see [if_group_fits_on_single_line]. +/// +/// # Examples +/// +/// Omits the trailing comma for the last array element if the `Group` fits on a single line +/// ``` +/// use rome_formatter::{format, format_args}; +/// use rome_formatter::prelude::*; +/// +/// let elements = format!(SimpleFormatContext::default(), [ +/// group_elements(&format_args![ +/// token("["), +/// soft_block_indent(&format_args![ +/// token("1,"), +/// soft_line_break_or_space(), +/// token("2,"), +/// soft_line_break_or_space(), +/// token("3"), +/// if_group_breaks(&token(",")) +/// ]), +/// token("]"), +/// ]) +/// ]).unwrap(); +/// +/// assert_eq!( +/// "[1, 2, 3]", +/// elements.print().as_code() +/// ); +/// ``` +/// +/// Prints the trailing comma for the last array element if the `Group` doesn't fit on a single line +/// ``` +/// use rome_formatter::{format_args, format, LineWidth}; +/// use rome_formatter::prelude::*; +/// +/// let context = SimpleFormatContext { +/// line_width: LineWidth::try_from(20).unwrap(), +/// ..SimpleFormatContext::default() +/// }; +/// +/// let elements = format!(context, [ +/// group_elements(&format_args![ +/// token("["), +/// soft_block_indent(&format_args![ +/// token("'A somewhat longer string to force a line break',"), +/// soft_line_break_or_space(), +/// token("2,"), +/// soft_line_break_or_space(), +/// token("3"), +/// if_group_breaks(&token(",")) +/// ]), +/// token("]"), +/// ]) +/// ]).unwrap(); +/// +/// let options = PrinterOptions { +/// print_width: LineWidth::try_from(20).unwrap(), +/// ..PrinterOptions::default() +/// }; +/// assert_eq!( +/// "[\n\t'A somewhat longer string to force a line break',\n\t2,\n\t3,\n]", +/// elements.print().as_code() +/// ); +/// ``` +#[inline] +pub fn if_group_breaks(content: &Content) -> IfGroupBreaks +where + Content: Format, +{ + IfGroupBreaks { + content: Argument::new(content), + group_id: None, + mode: PrintMode::Expanded, + } +} + +/// Adds a conditional content specific for `Group`s that fit on a single line. The content isn't +/// emitted for `Group`s spanning multiple lines. +/// +/// See [if_group_breaks] if you're looking for a way to print content only for groups spanning multiple lines. +/// +/// # Examples +/// +/// Adds the trailing comma for the last array element if the `Group` fits on a single line +/// ``` +/// use rome_formatter::{format, format_args}; +/// use rome_formatter::prelude::*; +/// +/// let formatted = format!(SimpleFormatContext::default(), [ +/// group_elements(&format_args![ +/// token("["), +/// soft_block_indent(&format_args![ +/// token("1,"), +/// soft_line_break_or_space(), +/// token("2,"), +/// soft_line_break_or_space(), +/// token("3"), +/// if_group_fits_on_line(&token(",")) +/// ]), +/// token("]"), +/// ]) +/// ]).unwrap(); +/// +/// assert_eq!( +/// "[1, 2, 3,]", +/// formatted.print().as_code() +/// ); +/// ``` +/// +/// Omits the trailing comma for the last array element if the `Group` doesn't fit on a single line +/// ``` +/// use rome_formatter::{format, format_args, LineWidth}; +/// use rome_formatter::prelude::*; +/// +/// let context = SimpleFormatContext { +/// line_width: LineWidth::try_from(20).unwrap(), +/// ..SimpleFormatContext::default() +/// }; +/// +/// let formatted = format!(context, [ +/// group_elements(&format_args![ +/// token("["), +/// soft_block_indent(&format_args![ +/// token("'A somewhat longer string to force a line break',"), +/// soft_line_break_or_space(), +/// token("2,"), +/// soft_line_break_or_space(), +/// token("3"), +/// if_group_fits_on_line(&token(",")) +/// ]), +/// token("]"), +/// ]) +/// ]).unwrap(); +/// +/// assert_eq!( +/// "[\n\t'A somewhat longer string to force a line break',\n\t2,\n\t3\n]", +/// formatted.print().as_code() +/// ); +/// ``` +#[inline] +pub fn if_group_fits_on_line(flat_content: &Content) -> IfGroupBreaks +where + Content: Format, +{ + IfGroupBreaks { + mode: PrintMode::Flat, + group_id: None, + content: Argument::new(flat_content), + } +} + +#[derive(Copy, Clone)] +pub struct IfGroupBreaks<'a, Context> { + content: Argument<'a, Context>, + group_id: Option, + mode: PrintMode, +} + +impl IfGroupBreaks<'_, Context> { + /// Inserts some content that the printer only prints if the group with the specified `group_id` + /// is printed in multiline mode. The referred group must appear before this element in the document + /// but doesn't have to one of its ancestors. + /// + /// # Examples + /// + /// Prints the trailing comma if the array group doesn't fit. The `group_id` is necessary + /// because `fill` creates an implicit group around each item and tries to print the item in flat mode. + /// The item `[4]` in this example fits on a single line but the trailing comma should still be printed + /// + /// ``` + /// use rome_formatter::{format, format_args, write, LineWidth}; + /// use rome_formatter::prelude::*; + /// + /// let context = SimpleFormatContext { + /// line_width: LineWidth::try_from(20).unwrap(), + /// ..SimpleFormatContext::default() + /// }; + /// + /// let formatted = format!(context, [format_with(|f| { + /// let group_id = f.group_id("array"); + /// + /// write!(f, [ + /// group_elements( + /// &format_args![ + /// token("["), + /// soft_block_indent(&format_with(|f| { + /// f.fill(soft_line_break_or_space()) + /// .entry(&token("1,")) + /// .entry(&token("234568789,")) + /// .entry(&token("3456789,")) + /// .entry(&format_args!( + /// token("["), + /// soft_block_indent(&token("4")), + /// token("]"), + /// if_group_breaks(&token(",")).with_group_id(Some(group_id)) + /// )) + /// .finish() + /// })), + /// token("]") + /// ], + /// ).with_group_id(Some(group_id)) + /// ]) + /// })]).unwrap(); + /// + /// assert_eq!( + /// "[\n\t1, 234568789,\n\t3456789, [4],\n]", + /// formatted.print().as_code() + /// ); + /// ``` + pub fn with_group_id(mut self, group_id: Option) -> Self { + self.group_id = group_id; + self + } +} + +impl Format for IfGroupBreaks<'_, Context> { + fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { + let mut buffer = VecBuffer::new(f.state_mut()); + + buffer.write_fmt(Arguments::from(&self.content))?; + + if buffer.is_empty() { + return Ok(()); + } + + let content = buffer.into_element(); + f.write_element(FormatElement::ConditionalGroupContent( + ConditionalGroupContent::new(content, self.mode).with_group_id(self.group_id), + )) + } +} + +impl std::fmt::Debug for IfGroupBreaks<'_, Context> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let name = match self.mode { + PrintMode::Flat => "IfGroupFitsOnLine", + PrintMode::Expanded => "IfGroupBreaks", + }; + + f.debug_struct(name) + .field("group_id", &self.group_id) + .field("content", &"{{content}}") + .finish() + } +} + +/// Utility for formatting some content with an inline lambda function. +#[derive(Copy, Clone)] +pub struct FormatWith { + formatter: T, + context: PhantomData, +} + +impl Format for FormatWith +where + T: Fn(&mut Formatter) -> FormatResult<()>, +{ + #[inline] + fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { + (self.formatter)(f) + } +} + +impl std::fmt::Debug for FormatWith { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_tuple("FormatWith").field(&"{{formatter}}").finish() + } +} + +/// Creates an object implementing `Format` that calls the passed closure to perform the formatting. +/// +/// # Examples +/// +/// ``` +/// use rome_formatter::prelude::*; +/// use rome_formatter::{SimpleFormatContext, format, write}; +/// use rome_rowan::TextSize; +/// +/// struct MyFormat { +/// items: Vec<&'static str>, +/// } +/// +/// impl Format for MyFormat { +/// fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { +/// write!(f, [ +/// token("("), +/// block_indent(&format_with(|f| { +/// let separator = space_token(); +/// let mut join = f.join_with(&separator); +/// +/// for item in &self.items { +/// join.entry(&format_with(|f| write!(f, [dynamic_token(item, TextSize::default())]))); +/// } +/// join.finish() +/// })), +/// token(")") +/// ]) +/// } +/// } +/// +/// let formatted = format!(SimpleFormatContext::default(), [MyFormat { items: vec!["a", "b", "c"]}]).unwrap(); +/// +/// assert_eq!("(\n\ta b c\n)", formatted.print().as_code()); +/// ``` +pub const fn format_with(formatter: T) -> FormatWith +where + T: Fn(&mut Formatter) -> FormatResult<()>, +{ + FormatWith { + formatter, + context: PhantomData, + } +} + +/// Creates an inline `Format` object that can only be formatted once. +/// +/// This can be useful in situation where the borrow checker doesn't allow you to use [`format_with`] +/// because the code formatting the content consumes the value and cloning the value is too expensive. +/// An example of this is if you want to nest a `FormatElement` or non-cloneable `Iterator` inside of a +/// `block_indent` as shown can see in the examples section. +/// +/// # Panics +/// +/// Panics if the object gets formatted more than once. +/// +/// # Example +/// +/// ``` +/// use rome_formatter::prelude::*; +/// use rome_formatter::{SimpleFormatContext, format, write, Buffer}; +/// +/// struct MyFormat; +/// +/// fn generate_values() -> impl Iterator { +/// vec![token("1"), token("2"), token("3"), token("4")].into_iter() +/// } +/// +/// impl Format for MyFormat { +/// fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { +/// let mut values = generate_values(); +/// +/// let first = values.next(); +/// +/// // Formats the first item outside of the block and all other items inside of the block, +/// // separated by line breaks +/// write!(f, [ +/// first, +/// block_indent(&format_once(|f| { +/// // Using format_with isn't possible here because the iterator gets consumed here +/// f.join_with(&hard_line_break()).entries(values).finish() +/// })), +/// ]) +/// } +/// } +/// +/// let formatted = format!(SimpleFormatContext::default(), [MyFormat]).unwrap(); +/// +/// assert_eq!("1\n\t2\n\t3\n\t4\n", formatted.print().as_code()); +/// ``` +/// +/// Formatting the same value twice results in a panic. +/// +/// ```panics +/// use rome_formatter::prelude::*; +/// use rome_formatter::{SimpleFormatContext, format, write, Buffer}; +/// use rome_rowan::TextSize; +/// +/// let mut count = 0; +/// +/// let value = format_once(|f| { +/// write!(f, [dynamic_token(&std::format!("Formatted {count}."), TextSize::default())]) +/// }); +/// +/// format!(SimpleFormatContext::default(), [value]).expect("Formatting once works fine"); +/// +/// // Formatting the value more than once panics +/// format!(SimpleFormatContext::default(), [value]); +/// ``` +pub const fn format_once(formatter: T) -> FormatOnce +where + T: FnOnce(&mut Formatter) -> FormatResult<()>, +{ + FormatOnce { + formatter: Cell::new(Some(formatter)), + context: PhantomData, + } +} + +pub struct FormatOnce { + formatter: Cell>, + context: PhantomData, +} + +impl Format for FormatOnce +where + T: FnOnce(&mut Formatter) -> FormatResult<()>, +{ #[inline] - pub fn entry(&mut self, element: FormatElement) { - if element.is_empty() { - return; + fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { + let formatter = self.formatter.take().expect("Tried to format a `format_once` at least twice. This is not allowed. You may want to use `format_with` or `format.memoized` instead."); + + (formatter)(f) + } +} + +impl std::fmt::Debug for FormatOnce { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_tuple("FormatOnce").field(&"{{formatter}}").finish() + } +} + +/// Builder to join together a sequence of content. +/// See [Formatter::join] +#[must_use = "must eventually call `finish()` on Format builders"] +pub struct JoinBuilder<'fmt, 'buf, Separator, Context> { + result: FormatResult<()>, + fmt: &'fmt mut Formatter<'buf, Context>, + with: Option, + has_elements: bool, +} + +impl<'fmt, 'buf, Separator, Context> JoinBuilder<'fmt, 'buf, Separator, Context> +where + Separator: Format, +{ + /// Creates a new instance that joins the elements without a separator + pub(super) fn new(fmt: &'fmt mut Formatter<'buf, Context>) -> Self { + Self { + result: Ok(()), + fmt, + has_elements: false, + with: None, } + } - if self.elements.is_empty() && self.size_hint.is_some() { - // SAFETY: Guaranteed by the `is_some` check above - let size_hint = self.size_hint.unwrap(); + /// Creates a new instance that prints the passed separator between every two entries. + pub(super) fn with_separator(fmt: &'fmt mut Formatter<'buf, Context>, with: Separator) -> Self { + Self { + result: Ok(()), + fmt, + has_elements: false, + with: Some(with), + } + } - match element { - FormatElement::List(list) => { - self.elements = list.into_vec(); - self.elements.reserve(size_hint - 1); + /// Adds a new entry to the join output. + pub fn entry(&mut self, entry: &dyn Format) -> &mut Self { + self.result = self.result.and_then(|_| { + if let Some(with) = &self.with { + if self.has_elements { + with.fmt(self.fmt)?; } - item => { - self.elements.reserve(size_hint); - self.elements.push(item); - } - } - } else { - match element { - FormatElement::List(list) => self.elements.extend(list.into_vec()), - item => self.elements.push(item), } + self.has_elements = true; + + entry.fmt(self.fmt) + }); + + self + } + + /// Adds the contents of an iterator of entries to the join output. + pub fn entries(&mut self, entries: I) -> &mut Self + where + F: Format, + I: IntoIterator, + { + for entry in entries { + self.entry(&entry); } + + self } - #[inline] - pub fn size_hint(&mut self, hint: (usize, Option)) { - let (lower_bound, upper_bound) = hint; - - if let Some(upper_bound) = upper_bound { - debug_assert!(lower_bound <= upper_bound, "Expected lower bound {lower_bound} to be less than or equal to upper bound {upper_bound}"); - self.size_hint = Some(upper_bound); - } else { - self.size_hint = Some(lower_bound); + /// Finishes the output and returns any error encountered. + pub fn finish(&mut self) -> FormatResult<()> { + self.result + } +} + +/// Builder to join together nodes that ensures that nodes separated by empty lines continue +/// to be separated by empty lines in the formatted output. +#[must_use = "must eventually call `finish()` on Format builders"] +pub struct JoinNodesBuilder<'fmt, 'buf, Separator, Context> { + result: FormatResult<()>, + /// The separator to insert between nodes. Either a soft or hard line break + separator: Separator, + fmt: &'fmt mut Formatter<'buf, Context>, + has_elements: bool, +} + +impl<'fmt, 'buf, Separator, Context> JoinNodesBuilder<'fmt, 'buf, Separator, Context> +where + Separator: Format, +{ + pub(super) fn new(separator: Separator, fmt: &'fmt mut Formatter<'buf, Context>) -> Self { + Self { + result: Ok(()), + separator, + fmt, + has_elements: false, } } - #[inline] - pub fn finish(mut self) -> FormatElement { - if self.elements.is_empty() { - empty_element() - } else if self.elements.len() == 1 { - // Safety: Guaranteed to succeed by the length check above - self.elements.pop().unwrap() - } else { - FormatElement::List(List::new(self.elements)) + /// Adds a new node with the specified formatted content to the output, respecting any new lines + /// that appear before the node in the input source. + pub fn entry(&mut self, node: &SyntaxNode, content: &dyn Format) { + self.result = self.result.and_then(|_| { + let mut buffer = PreambleBuffer::new( + self.fmt, + format_with(|f| { + if self.has_elements { + if get_lines_before(node) > 1 { + write!(f, [empty_line()])?; + } else { + self.separator.fmt(f)?; + } + } + + Ok(()) + }), + ); + + write!(buffer, [content])?; + + self.has_elements = self.has_elements || buffer.did_write_preamble(); + + Ok(()) + }); + } + + /// Adds an iterator of entries to the output. Each entry is a `(node, content)` tuple. + pub fn entries(&mut self, entries: I) -> &mut Self + where + L: Language, + F: Format, + I: IntoIterator, F)>, + { + for (node, content) in entries { + self.entry(&node, &content) } + + self + } + + pub fn finish(&mut self) -> FormatResult<()> { + self.result + } +} + +/// Get the number of line breaks between two consecutive SyntaxNodes in the tree +pub fn get_lines_before(next_node: &SyntaxNode) -> usize { + // Count the newlines in the leading trivia of the next node + if let Some(leading_trivia) = next_node.first_leading_trivia() { + leading_trivia + .pieces() + .take_while(|piece| { + // Stop at the first comment piece, the comment printer + // will handle newlines between the comment and the node + !piece.is_comments() + }) + .filter(|piece| piece.is_newline()) + .count() + } else { + 0 + } +} + +/// Builder to fill as many elements as possible on a single line. +#[must_use = "must eventually call `finish()` on Format builders"] +pub struct FillBuilder<'fmt, 'buf, Context> { + result: FormatResult<()>, + fmt: &'fmt mut Formatter<'buf, Context>, + + /// The separator to use to join the elements + separator: FormatElement, + items: Vec, +} + +impl<'a, 'buf, Context> FillBuilder<'a, 'buf, Context> { + pub(crate) fn new( + fmt: &'a mut Formatter<'buf, Context>, + separator: Separator, + ) -> Self + where + Separator: Format, + { + let mut buffer = VecBuffer::new(fmt.state_mut()); + let result = write!(buffer, [separator]); + let separator = buffer.into_element(); + + Self { + result, + fmt, + separator, + items: vec![], + } + } + + /// Adds an iterator of entries to the fill output. + pub fn entries(&mut self, entries: I) -> &mut Self + where + F: Format, + I: IntoIterator, + { + for entry in entries { + self.entry(&entry); + } + + self + } + + /// Adds a new entry to the fill output. + pub fn entry(&mut self, entry: &dyn Format) -> &mut Self { + self.result = self.result.and_then(|_| { + let mut buffer = VecBuffer::new(self.fmt.state_mut()); + write!(buffer, [entry])?; + + let item = buffer.into_element(); + + if !item.is_empty() { + self.items.push(item); + } + + Ok(()) + }); + + self + } + + /// Finishes the output and returns any error encountered + pub fn finish(&mut self) -> FormatResult<()> { + self.result.and_then(|_| { + let mut items = std::mem::take(&mut self.items); + + match items.len() { + 0 => Ok(()), + 1 => self.fmt.write_element(items.pop().unwrap()), + _ => self.fmt.write_element(FormatElement::Fill(Box::new(Fill { + list: List::new(items), + separator: std::mem::replace( + &mut self.separator, + FormatElement::List(List::default()), + ), + }))), + } + }) + } +} + +/// The first variant is the most flat, and the last is the most expanded variant. +/// See [`best_fitting!`] macro for a more in-detail documentation +#[derive(Copy, Clone)] +pub struct BestFitting<'a, Context> { + variants: Arguments<'a, Context>, +} + +impl<'a, Context> BestFitting<'a, Context> { + /// Creates a new best fitting IR with the given variants. The method itself isn't unsafe + /// but it is to discourage people from using it because the printer will panic if + /// the slice doesn't contain at least the least and most expanded variants. + /// + /// You're looking for a way to create a `BestFitting` object, use the `best_fitting![least_expanded, most_expanded]` macro. + /// + /// ## Safety + /// The slice must contain at least two variants. + pub unsafe fn from_arguments_unchecked(variants: Arguments<'a, Context>) -> Self { + debug_assert!( + variants.0.len() >= 2, + "Requires at least the least expanded and most expanded variants" + ); + + Self { variants } + } +} + +impl Format for BestFitting<'_, Context> { + fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { + let mut buffer = VecBuffer::new(f.state_mut()); + let variants = self.variants.items(); + + let mut formatted_variants = Vec::with_capacity(variants.len()); + + for variant in variants { + buffer.write_fmt(Arguments::from(&*variant))?; + + formatted_variants.push(buffer.take()); + } + + // SAFETY: The constructor guarantees that there are always at least two variants. It's, therefore, + // safe to call into the unsafe `from_vec_unchecked` function + let element = unsafe { + FormatElement::BestFitting(format_element::BestFitting::from_vec_unchecked( + formatted_variants, + )) + }; + + f.write_element(element)?; + + Ok(()) } } diff --git a/crates/rome_formatter/src/format_element.rs b/crates/rome_formatter/src/format_element.rs index 7a90283a7fa..bb4565d1010 100644 --- a/crates/rome_formatter/src/format_element.rs +++ b/crates/rome_formatter/src/format_element.rs @@ -1,1100 +1,26 @@ -use crate::builders::ConcatBuilder; -use crate::intersperse::{Intersperse, IntersperseFn}; -use crate::{format_elements, GroupId, TextRange, TextSize}; +use crate::{GroupId, TextSize}; #[cfg(target_pointer_width = "64")] use rome_rowan::static_assert; -use rome_rowan::{ - Language, SyntaxNode, SyntaxToken, SyntaxTokenText, SyntaxTriviaPieceComments, TextLen, -}; +use rome_rowan::SyntaxTokenText; use std::borrow::Cow; use std::fmt::{self, Debug, Formatter}; use std::ops::Deref; type Content = Box; -/// Format element that doesn't represent any content. -/// -/// Can be helpful if you need to return a `FormatElement` (e.g. in an else branch) but don't want -/// to show any content. -pub fn empty_element() -> FormatElement { - FormatElement::Empty -} - -/// A line break that only gets printed if the enclosing `Group` doesn't fit on a single line. -/// It's omitted if the enclosing `Group` fits on a single line. -/// A soft line break is identical to a hard line break when not enclosed inside of a `Group`. -/// -/// ## Examples -/// -/// Soft line breaks are omitted if the enclosing `Group` fits on a single line -/// -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![token("a,"), soft_line_break(), token("b"),]); -/// -/// assert_eq!( -/// "a,b", -/// Formatted::new(elements, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ); -/// ``` -/// See [soft_line_break_or_space] if you want to insert a space between the elements if the enclosing -/// `Group` fits on a single line. -/// -/// Soft line breaks are emitted if the enclosing `Group` doesn't fit on a single line -/// ``` -/// use rome_formatter::{Formatted, LineWidth}; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![ -/// token("a long word,"), -/// soft_line_break(), -/// token("so that the group doesn't fit on a single line"), -/// ]); -/// -/// let options = PrinterOptions { -/// print_width: LineWidth::try_from(10).unwrap(), -/// ..PrinterOptions::default() -/// }; -/// -/// assert_eq!( -/// "a long word,\nso that the group doesn't fit on a single line", -/// Formatted::new(elements, options).print().as_code() -/// ); -/// ``` -#[inline] -pub const fn soft_line_break() -> FormatElement { - FormatElement::Line(Line::new(LineMode::Soft)) -} - -/// A forced line break that are always printed. A hard line break forces any enclosing `Group` -/// to be printed over multiple lines. -/// -/// ## Examples -/// -/// It forces a line break, even if the enclosing `Group` would otherwise fit on a single line. -/// ``` -/// use rome_formatter::*; -/// use rome_formatter::prelude::PrinterOptions; -/// -/// let elements = group_elements(format_elements![ -/// token("a,"), -/// hard_line_break(), -/// token("b"), -/// hard_line_break() -/// ]); -/// -/// assert_eq!( -/// "a,\nb\n", -/// Formatted::new(elements, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ); -/// ``` -#[inline] -pub const fn hard_line_break() -> FormatElement { - FormatElement::Line(Line::new(LineMode::Hard)) -} - -/// A forced empty line. An empty line inserts enough line breaks in the output for -/// the previous and next element to be separated by an empty line. -/// -/// ## Examples -/// -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![ -/// token("a,"), -/// empty_line(), -/// token("b"), -/// empty_line() -/// ]); -/// -/// assert_eq!( -/// "a,\n\nb\n\n", -/// Formatted::new(elements, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ); -/// ``` -#[inline] -pub const fn empty_line() -> FormatElement { - FormatElement::Line(Line::new(LineMode::Empty)) -} - -/// A line break if the enclosing `Group` doesn't fit on a single line, a space otherwise. -/// -/// ## Examples -/// -/// The line breaks are emitted as spaces if the enclosing `Group` fits on a a single line: -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![ -/// token("a,"), -/// soft_line_break_or_space(), -/// token("b"), -/// ]); -/// -/// assert_eq!( -/// "a, b", -/// Formatted::new(elements, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ); -/// ``` -/// -/// The printer breaks the lines if the enclosing `Group` doesn't fit on a single line: -/// ``` -/// use rome_formatter::{Formatted, LineWidth}; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![ -/// token("a long word,"), -/// soft_line_break_or_space(), -/// token("so that the group doesn't fit on a single line"), -/// ]); -/// -/// let options = PrinterOptions { -/// print_width: LineWidth::try_from(10).unwrap(), -/// ..PrinterOptions::default() -/// }; -/// -/// assert_eq!( -/// "a long word,\nso that the group doesn't fit on a single line", -/// Formatted::new(elements, options).print().as_code() -/// ); -/// ``` -#[inline] -pub const fn soft_line_break_or_space() -> FormatElement { - FormatElement::Line(Line::new(LineMode::SoftOrSpace)) -} - -/// Creates a token that gets written as is to the output. Make sure to properly escape the text if -/// it's user generated (e.g. a string and not a language keyword). -/// -/// ## Line feeds -/// Tokens may contain line breaks but they must use the line feeds (`\n`). -/// The [crate::Printer] converts the line feed characters to the character specified in the [crate::PrinterOptions]. -/// -/// ## Examples -/// -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// let elements = token("Hello World"); -/// -/// assert_eq!( -/// "Hello World", -/// Formatted::new(elements, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ); -/// ``` -/// -/// Printing a string literal as a literal requires that the string literal is properly escaped and -/// enclosed in quotes (depending on the target language). -/// -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// -/// // the tab must be encoded as \\t to not literally print a tab character ("Hello{tab}World" vs "Hello\tWorld") -/// let elements = token("\"Hello\\tWorld\""); -/// -/// assert_eq!(r#""Hello\tWorld""#, Formatted::new(elements, PrinterOptions::default()).print().as_code()); -/// ``` -#[inline] -pub const fn token(text: &'static str) -> FormatElement { - if text.is_empty() { - FormatElement::Empty - } else { - FormatElement::Token(Token::new_static(text)) - } -} - -/// Push a [FormatElement] to the end of the current line -/// -/// ## Examples -/// -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// -/// let elements = format_elements![token("a"), line_suffix(token("c")), token("b")]; -/// -/// assert_eq!( -/// "abc", -/// Formatted::new(elements, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ); -/// ``` -#[inline] -pub fn line_suffix(element: impl Into) -> FormatElement { - FormatElement::LineSuffix(Box::new(element.into())) -} - -/// Inserts a boundary for line suffixes that forces to print all pending line suffixes. Helpful -/// if a line sufix shouldn't pass a certain point. -/// -/// ## Examples -/// -/// Forces the line suffix "c" to be printed before the token `d`. -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// -/// let elements = format_elements![token("a"), line_suffix(token("c")), token("b"), line_suffix_boundary(), token("d")]; -/// -/// assert_eq!( -/// "abc\nd", -/// Formatted::new(elements, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ); -/// ``` -pub const fn line_suffix_boundary() -> FormatElement { - FormatElement::LineSuffixBoundary -} - -/// Mark a [FormatElement] as being a piece of trivia -/// -/// This does not directly influence how this content will be printed, but some -/// parts of the formatter may chose to handle this element in a specific way -/// -/// ## Examples -/// -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![ -/// comment(empty_line()), -/// token("a"), -/// soft_line_break_or_space(), -/// token("b") -/// ]); -/// -/// assert_eq!( -/// "\na b", -/// Formatted::new(elements, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ); -/// ``` -#[inline] -pub fn comment(element: impl Into) -> FormatElement { - FormatElement::Comment(Box::new(element.into())) -} - -/// Inserts a single space. Allows to separate different tokens. -/// -/// ## Examples -/// -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// -/// // the tab must be encoded as \\t to not literally print a tab character ("Hello{tab}World" vs "Hello\tWorld") -/// let elements = format_elements![token("a"), space_token(), token("b")]; -/// -/// assert_eq!("a b", Formatted::new(elements, PrinterOptions::default()).print().as_code()); -/// ``` -#[inline] -pub const fn space_token() -> FormatElement { - FormatElement::Space -} - -/// Concatenates the content of multiple [FormatElement]s. -/// -/// ## Examples -/// -/// ```rust -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// let expr = concat_elements(vec![ -/// token("a"), -/// space_token(), -/// token("+"), -/// space_token(), -/// token("b"), -/// ]); -/// -/// assert_eq!( -/// "a + b", -/// Formatted::new(expr, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ) -/// ``` -pub fn concat_elements(elements: I) -> FormatElement -where - I: IntoIterator, -{ - let elements = elements.into_iter(); - let mut builder = ConcatBuilder::new(); - - builder.size_hint(elements.size_hint()); - - for element in elements { - builder.entry(element); - } - - builder.finish() -} - -/// Concatenates a list of [FormatElement]s with spaces and line breaks to fit -/// them on as few lines as possible. Each element introduces a conceptual group. The printer -/// first tries to print the item in flat mode but then prints it in expanded mode if it doesn't fit. -/// -/// The separator should be an item that breaks, e.g. [soft_line_break], as the printer relies on -/// the separator breaking to fill print the items. -/// -/// ## Examples -/// -/// ```rust -/// use rome_formatter::prelude::*; -/// use rome_formatter::Formatted; -/// use std::str::from_utf8; -/// -/// let a = from_utf8(&[b'a'; 30]).unwrap(); -/// let b = from_utf8(&[b'b'; 30]).unwrap(); -/// let c = from_utf8(&[b'c'; 30]).unwrap(); -/// let d = from_utf8(&[b'd'; 30]).unwrap(); -/// let expr = fill_elements(soft_line_break_or_space(), [token(a), token(b), token(c), token(d)]); -/// -/// assert_eq!( -/// format!("{a} {b}\n{c} {d}"), -/// Formatted::new(expr, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ) -/// ``` -/// ```rust -/// use rome_formatter::prelude::*; -/// use rome_formatter::Formatted; -/// use std::str::from_utf8; -/// -/// let a = "Important: "; -/// let b = "Please do not commit memory bugs such as segfaults, buffer overflows, etc. otherwise you "; -/// let c = "will"; -/// let d = " be reprimanded"; -/// let expr = fill_elements(soft_line_break(), [token(a), token(b), token(c), token(d)]); -/// -/// assert_eq!( -/// format!("{a}\n{b}\n{c}{d}"), -/// Formatted::new(expr, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ) -/// ``` -pub fn fill_elements>( - separator: TSep, - elements: impl IntoIterator, -) -> FormatElement { - let mut list: Vec<_> = elements.into_iter().collect(); - match list.len() { - 0 => empty_element(), - 1 => list.pop().unwrap(), - _ => FormatElement::Fill(Box::new(Fill { - list: List::new(list), - separator: separator.into(), - })), - } -} - -/// Joins the elements by placing a given separator between elements. -/// -/// ## Examples -/// -/// Joining different tokens by separating them with a comma and a space. -/// -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// -/// let separator = concat_elements(vec![token(","), space_token()]); -/// let elements = join_elements( -/// separator, -/// vec![token("1"), token("2"), token("3"), token("4")], -/// ); -/// -/// assert_eq!( -/// "1, 2, 3, 4", -/// Formatted::new(elements, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ); -/// ``` -#[inline] -pub fn join_elements(separator: TSep, elements: I) -> FormatElement -where - TSep: Into, - I: IntoIterator, -{ - concat_elements(Intersperse::new( - elements.into_iter().filter(|e| !e.is_empty()), - separator.into(), - )) -} - -/// It adds a level of indentation to the given content -/// -/// It doesn't add any line breaks at the edges of the content, meaning that -/// the line breaks have to be manually added. -/// -/// This helper should be used only in rare cases, instead you should rely more on -/// [block_indent] and [soft_block_indent] -/// -/// ## Examples -/// -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// -/// let block = (format_elements![ -/// token("switch {"), -/// block_indent(format_elements![ -/// token("default:"), -/// indent(format_elements![ -/// // this is where we want to use a -/// hard_line_break(), -/// token("break;"), -/// ]) -/// ]), -/// token("}"), -/// ]); -/// -/// assert_eq!( -/// "switch {\n\tdefault:\n\t\tbreak;\n}", -/// Formatted::new(block, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ); -/// ``` -#[inline] -pub fn indent>(content: T) -> FormatElement { - let content = content.into(); - - if content.is_empty() { - content - } else { - format_elements![Indent::new(format_elements![content])] - } -} - -/// Inserts a hard line break before and after the content and increases the indention level for the content by one. -/// -/// Block indents indent a block of code, such as in a function body, and therefore insert a line -/// break before and after the content. -/// -/// Doesn't create an indention if the passed in content is [FormatElement.is_empty]. -/// -/// ## Examples -/// -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// -/// let block = (format_elements![ -/// token("{"), -/// block_indent(format_elements![ -/// token("let a = 10;"), -/// hard_line_break(), -/// token("let c = a + 5;"), -/// ]), -/// token("}"), -/// ]); -/// -/// assert_eq!( -/// "{\n\tlet a = 10;\n\tlet c = a + 5;\n}", -/// Formatted::new(block, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ); -/// ``` -#[inline] -pub fn block_indent>(content: T) -> FormatElement { - let content = content.into(); - - if content.is_empty() { - content - } else { - format_elements![ - Indent::new(format_elements![hard_line_break(), content]), - hard_line_break(), - ] - } -} - -/// Indents the content by inserting a line break before and after the content and increasing -/// the indention level for the content by one if the enclosing group doesn't fit on a single line. -/// Doesn't change the formatting if the enclosing group fits on a single line. -/// -/// ## Examples -/// -/// Indents the content by one level and puts in new lines if the enclosing `Group` doesn't fit on a single line -/// -/// ``` -/// use rome_formatter::{Formatted, LineWidth}; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![ -/// token("["), -/// soft_block_indent(format_elements![ -/// token("'First string',"), -/// soft_line_break_or_space(), -/// token("'second string',"), -/// ]), -/// token("]"), -/// ]); -/// -/// let options = PrinterOptions { -/// print_width: LineWidth::try_from(10).unwrap(), -/// ..PrinterOptions::default() -/// }; -/// -/// assert_eq!( -/// "[\n\t'First string',\n\t'second string',\n]", -/// Formatted::new(elements, options).print().as_code() -/// ); -/// ``` -/// -/// Doesn't change the formatting if the enclosing `Group` fits on a single line -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![ -/// token("["), -/// soft_block_indent(format_elements![ -/// token("5,"), -/// soft_line_break_or_space(), -/// token("10"), -/// ]), -/// token("]"), -/// ]); -/// -/// assert_eq!( -/// "[5, 10]", -/// Formatted::new(elements, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ); -/// ``` -#[inline] -pub fn soft_block_indent>(content: T) -> FormatElement { - let content = content.into(); - - if content.is_empty() { - content - } else { - format_elements![ - Indent::new(format_elements![soft_line_break(), content]), - soft_line_break(), - ] - } -} - -/// If the enclosing `Group` doesn't fit on a single line, inserts a line break and indent. -/// Otherwise, just inserts a space. -/// -/// Line indents are used to break a single line of code, and therefore only insert a line -/// break before the content and not after the content. -/// -/// ## Examples -/// -/// Indents the content by one level and puts in new lines if the enclosing `Group` doesn't -/// fit on a single line. Otherwise, just inserts a space. -/// -/// ``` -/// use rome_formatter::{Formatted, LineWidth}; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![ -/// token("name"), -/// space_token(), -/// token("="), -/// soft_line_indent_or_space(format_elements![ -/// token("firstName"), -/// space_token(), -/// token("+"), -/// space_token(), -/// token("lastName"), -/// ]), -/// ]); -/// -/// let options = PrinterOptions { -/// print_width: LineWidth::try_from(10).unwrap(), -/// ..PrinterOptions::default() -/// }; -/// -/// assert_eq!( -/// "name =\n\tfirstName + lastName", -/// Formatted::new(elements, options).print().as_code() -/// ); -/// ``` -/// -/// Only adds a space if the enclosing `Group` fits on a single line -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![ -/// token("a"), -/// space_token(), -/// token("="), -/// soft_line_indent_or_space(format_elements![token("10")]), -/// ]); -/// -/// assert_eq!( -/// "a = 10", -/// Formatted::new(elements, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ); -/// ``` -#[inline] -pub fn soft_line_indent_or_space>(content: T) -> FormatElement { - let content = content.into(); - - if content.is_empty() { - content - } else { - format_elements![Indent::new(format_elements![ - soft_line_break_or_space(), - content - ])] - } -} - -/// Creates a logical `Group` around the content that should either consistently be printed on a single line -/// or broken across multiple lines. -/// -/// The printer will try to print the content of the `Group` on a single line, ignoring all soft line breaks and -/// emitting spaces for soft line breaks or spaces. The printer tracks back if it isn't successful either -/// because it encountered a hard line break, or because printing the `Group` on a single line exceeds -/// the configured line width, and thus it must print all its content on multiple lines, -/// emitting line breaks for all line break kinds. -/// -/// ## Examples -/// -/// `Group` that fits on a single line -/// -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![ -/// token("["), -/// soft_block_indent(format_elements![ -/// token("1,"), -/// soft_line_break_or_space(), -/// token("2,"), -/// soft_line_break_or_space(), -/// token("3"), -/// ]), -/// token("]"), -/// ]); -/// -/// assert_eq!( -/// "[1, 2, 3]", -/// Formatted::new(elements, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ); -/// ``` -/// -/// The printer breaks the `Group` over multiple lines if its content doesn't fit on a single line -/// ``` -/// use rome_formatter::{Formatted, LineWidth}; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![ -/// token("["), -/// soft_block_indent(format_elements![ -/// token("'Good morning! How are you today?',"), -/// soft_line_break_or_space(), -/// token("2,"), -/// soft_line_break_or_space(), -/// token("3"), -/// ]), -/// token("]"), -/// ]); -/// -/// let options = PrinterOptions { -/// print_width: LineWidth::try_from(20).unwrap(), -/// ..PrinterOptions::default() -/// }; -/// -/// assert_eq!( -/// "[\n\t'Good morning! How are you today?',\n\t2,\n\t3\n]", -/// Formatted::new(elements, options).print().as_code() -/// ); -/// ``` -#[inline] -pub fn group_elements>(content: T) -> FormatElement { - group_elements_with_options(content.into(), GroupElementsOptions::default()) -} - -#[derive(Default, Clone, Debug)] -pub struct GroupElementsOptions { - pub group_id: Option, -} - -/// Creates a group with a specific id. Useful for cases where `if_group_breaks` and `if_group_fits_on_line` -/// shouldn't refer to the direct parent group. -pub fn group_elements_with_options( - content: FormatElement, - options: GroupElementsOptions, -) -> FormatElement { - if content.is_empty() { - content - } else { - let (leading, content, trailing) = content.split_trivia(); - - let group = Group::new(content).with_id(options.group_id); - - format_elements![leading, group, trailing] - } -} - -/// IR element that forces the parent group to print in expanded mode. -/// -/// Has no effect if used outside of a group or element that introduce implicit groups (fill element). -/// -/// ## Examples -/// -/// ``` -/// use rome_formatter::{Formatted, LineWidth}; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![ -/// token("["), -/// soft_block_indent(format_elements![ -/// token("'Good morning! How are you today?',"), -/// soft_line_break_or_space(), -/// token("2,"), -/// expand_parent(), // Forces the parent to expand -/// soft_line_break_or_space(), -/// token("3"), -/// ]), -/// token("]"), -/// ]); -/// -/// assert_eq!( -/// "[\n\t'Good morning! How are you today?',\n\t2,\n\t3\n]", -/// Formatted::new(elements, PrinterOptions::default()).print().as_code() -/// ); -/// ``` -/// -/// ## Prettier -/// Equivalent to Prettier's `break_parent` IR element -pub const fn expand_parent() -> FormatElement { - FormatElement::ExpandParent -} - -/// Adds a conditional content that is emitted only if it isn't inside an enclosing `Group` that -/// is printed on a single line. The element allows, for example, to insert a trailing comma after the last -/// array element only if the array doesn't fit on a single line. -/// -/// The element has no special meaning if used outside of a `Group`. In that case, the content is always emitted. -/// -/// If you're looking for a way to only print something if the `Group` fits on a single line see [if_group_fits_on_single_line]. -/// -/// ## Examples -/// -/// Omits the trailing comma for the last array element if the `Group` fits on a single line -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![ -/// token("["), -/// soft_block_indent(format_elements![ -/// token("1,"), -/// soft_line_break_or_space(), -/// token("2,"), -/// soft_line_break_or_space(), -/// token("3"), -/// if_group_breaks(token(",")) -/// ]), -/// token("]"), -/// ]); -/// assert_eq!( -/// "[1, 2, 3]", -/// Formatted::new(elements, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ); -/// ``` -/// -/// Prints the trailing comma for the last array element if the `Group` doesn't fit on a single line -/// ``` -/// use rome_formatter::{Formatted, LineWidth}; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![ -/// token("["), -/// soft_block_indent(format_elements![ -/// token("'A somewhat longer string to force a line break',"), -/// soft_line_break_or_space(), -/// token("2,"), -/// soft_line_break_or_space(), -/// token("3"), -/// if_group_breaks(token(",")) -/// ]), -/// token("]"), -/// ]); -/// -/// let options = PrinterOptions { -/// print_width: LineWidth::try_from(20).unwrap(), -/// ..PrinterOptions::default() -/// }; -/// assert_eq!( -/// "[\n\t'A somewhat longer string to force a line break',\n\t2,\n\t3,\n]", -/// Formatted::new(elements, options).print().as_code() -/// ); -/// ``` -#[inline] -pub fn if_group_breaks>(content: T) -> FormatElement { - if_group_breaks_impl(content.into(), None) -} - -/// Inserts some content that the printer only prints if the group with the specified `group_id` -/// is printed in multiline mode. The referred group must appear before this element in the document -/// but doesn't have to one of its ancestors. -/// -/// ## Examples -/// -/// Prints the trailing comma if the array group doesn't fit. The `group_id` is necessary -/// because `fill` creates an implicit group around each item and tries to print the item in flat mode. -/// The item `[4]` in this example fits on a single line but the trailing comma should still be printed -/// -/// ``` -/// use rome_formatter::{Formatted, LineWidth}; -/// use rome_formatter::prelude::*; -/// -/// let formatter = Formatter::<()>::default(); -/// let group_id = formatter.group_id("array"); -/// -/// let elements = group_elements_with_options(format_elements![ -/// token("["), -/// soft_block_indent(fill_elements(soft_line_break_or_space(), vec![ -/// format_elements![token("1,")], -/// format_elements![token("234568789,")], -/// format_elements![token("3456789,")], -/// format_elements![ -/// token("["), -/// soft_block_indent(token("4")), -/// token("]"), -/// if_group_with_id_breaks(token(","), group_id) -/// ], -/// ])), -/// token("]"), -/// ], GroupElementsOptions { group_id: Some(group_id) }); -/// -/// let options = PrinterOptions { -/// print_width: LineWidth::try_from(20).unwrap(), -/// ..PrinterOptions::default() -/// }; -/// assert_eq!( -/// "[\n\t1, 234568789,\n\t3456789, [4],\n]", -/// Formatted::new(elements, options).print().as_code() -/// ); -/// ``` -pub fn if_group_with_id_breaks(content: FormatElement, group_id: GroupId) -> FormatElement { - if_group_breaks_impl(content, Some(group_id)) -} - -fn if_group_breaks_impl(content: FormatElement, group_id: Option) -> FormatElement { - if content.is_empty() { - content - } else { - FormatElement::from( - ConditionalGroupContent::new(content, PrintMode::Expanded).with_group_id(group_id), - ) - } -} - -/// Adds a conditional content specific for `Group`s that fit on a single line. The content isn't -/// emitted for `Group`s spanning multiple lines. -/// -/// See [if_group_breaks] if you're looking for a way to print content only for groups spanning multiple lines. -/// -/// ## Examples -/// -/// Adds the trailing comma for the last array element if the `Group` fits on a single line -/// ``` -/// use rome_formatter::Formatted; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![ -/// token("["), -/// soft_block_indent(format_elements![ -/// token("1,"), -/// soft_line_break_or_space(), -/// token("2,"), -/// soft_line_break_or_space(), -/// token("3"), -/// if_group_fits_on_single_line(token(",")) -/// ]), -/// token("]"), -/// ]); -/// assert_eq!( -/// "[1, 2, 3,]", -/// Formatted::new(elements, PrinterOptions::default()) -/// .print() -/// .as_code() -/// ); -/// ``` -/// -/// Omits the trailing comma for the last array element if the `Group` doesn't fit on a single line -/// ``` -/// use rome_formatter::{Formatted, LineWidth}; -/// use rome_formatter::prelude::*; -/// -/// let elements = group_elements(format_elements![ -/// token("["), -/// soft_block_indent(format_elements![ -/// token("'A somewhat longer string to force a line break',"), -/// soft_line_break_or_space(), -/// token("2,"), -/// soft_line_break_or_space(), -/// token("3"), -/// if_group_fits_on_single_line(token(",")) -/// ]), -/// token("]"), -/// ]); -/// -/// let options = PrinterOptions { -/// print_width: LineWidth::try_from(20).unwrap(), -/// ..PrinterOptions::default() -/// }; -/// assert_eq!( -/// "[\n\t'A somewhat longer string to force a line break',\n\t2,\n\t3\n]", -/// Formatted::new(elements, options).print().as_code() -/// ); -/// ``` -#[inline] -pub fn if_group_fits_on_single_line(flat_content: TFlat) -> FormatElement -where - TFlat: Into, -{ - if_group_fits_on_line_impl(flat_content.into(), None) -} - -/// Inserts some content that the printer only prints if the group with the specified `group_id` -/// is printed in flat mode. -/// -#[inline] -pub fn if_group_with_id_fits_on_line(flat_content: FormatElement, id: GroupId) -> FormatElement { - if_group_fits_on_line_impl(flat_content, Some(id)) -} - -fn if_group_fits_on_line_impl( - flat_content: FormatElement, - group_id: Option, -) -> FormatElement { - if flat_content.is_empty() { - flat_content - } else { - FormatElement::from( - ConditionalGroupContent::new(flat_content, PrintMode::Flat).with_group_id(group_id), - ) - } -} - -/// Specialized version of [join_elements] for joining SyntaxNodes separated by a space, soft -/// line break or empty line depending on the input file. -/// -/// This functions inspects the input source and separates consecutive elements with either -/// a [soft_line_break_or_space] or [empty_line] depending on how many line breaks were -/// separating the elements in the original file. -#[inline] -pub fn join_elements_soft_line(elements: I) -> FormatElement -where - I: IntoIterator, FormatElement)>, - L: Language, -{ - join_elements_with(elements, soft_line_break_or_space) -} - -/// Specialized version of [join_elements] for joining SyntaxNodes separated by one or more -/// line breaks depending on the input file. -/// -/// This functions inspects the input source and separates consecutive elements with either -/// a [hard_line_break] or [empty_line] depending on how many line breaks were separating the -/// elements in the original file. -#[inline] -pub fn join_elements_hard_line(elements: I) -> FormatElement -where - I: IntoIterator, FormatElement)>, - L: Language, -{ - join_elements_with(elements, hard_line_break) -} - -/// Get the number of line breaks between two consecutive SyntaxNodes in the tree -pub fn get_lines_before(next_node: &SyntaxNode) -> usize { - // Count the newlines in the leading trivia of the next node - if let Some(leading_trivia) = next_node.first_leading_trivia() { - leading_trivia - .pieces() - .take_while(|piece| { - // Stop at the first comment piece, the comment printer - // will handle newlines between the comment and the node - !piece.is_comments() - }) - .filter(|piece| piece.is_newline()) - .count() - } else { - 0 - } -} - -#[inline] -pub fn join_elements_with(elements: I, separator: fn() -> FormatElement) -> FormatElement -where - I: IntoIterator, FormatElement)>, - L: Language, -{ - concat_elements(IntersperseFn::new( - elements.into_iter(), - |_, next_node, next_elem| { - if next_elem.is_empty() { - empty_element() - } else if get_lines_before(next_node) > 1 { - empty_line() - } else { - separator() - } - }, - )) -} - /// Language agnostic IR for formatting source code. /// /// Use the helper functions like [crate::space_token], [crate::soft_line_break] etc. defined in this file to create elements. #[derive(Clone, Eq, PartialEq)] pub enum FormatElement { - Empty, - /// A space token, see [crate::space_token] for documentation. Space, /// A new line, see [crate::soft_line_break], [crate::hard_line_break], and [crate::soft_line_break_or_space] for documentation. - Line(Line), + Line(LineMode), /// Indents the content one level deeper, see [crate::indent] for documentation and examples. - Indent(Indent), + Indent(Content), /// Creates a logical group where its content is either consistently printed: /// * on a single line: Omitting `LineMode::Soft` line breaks and printing spaces for `LineMode::SoftOrSpace` @@ -1141,7 +67,7 @@ pub enum FormatElement { BestFitting(BestFitting), } -#[derive(Clone, Eq, PartialEq)] +#[derive(Clone, Copy, Eq, PartialEq, Debug)] pub enum VerbatimKind { Unknown, Suppressed, @@ -1190,10 +116,9 @@ impl Verbatim { impl Debug for FormatElement { fn fmt(&self, fmt: &mut Formatter) -> fmt::Result { match self { - FormatElement::Empty => write!(fmt, "Empty"), FormatElement::Space => write!(fmt, "Space"), - FormatElement::Line(content) => content.fmt(fmt), - FormatElement::Indent(content) => content.fmt(fmt), + FormatElement::Line(content) => fmt.debug_tuple("Line").field(content).finish(), + FormatElement::Indent(content) => fmt.debug_tuple("Indent").field(content).finish(), FormatElement::Group(content) => { write!(fmt, "Group")?; content.fmt(fmt) @@ -1223,24 +148,6 @@ impl Debug for FormatElement { } } -/// Inserts a new line -#[derive(Clone, Eq, PartialEq)] -pub struct Line { - pub mode: LineMode, -} - -impl Debug for Line { - fn fmt(&self, fmt: &mut Formatter) -> fmt::Result { - write!(fmt, "Line({:?})", self.mode) - } -} - -impl Line { - pub const fn new(mode: LineMode) -> Self { - Self { mode } - } -} - #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum LineMode { /// See [soft_line_break_or_space] for documentation. @@ -1253,28 +160,8 @@ pub enum LineMode { Empty, } -/// Increases the indention by one; see [indented_with_soft_break] and [indented_with_hard_break]. -#[derive(Clone, Eq, PartialEq)] -pub struct Indent { - pub(crate) content: Content, -} - -impl Debug for Indent { - fn fmt(&self, fmt: &mut Formatter) -> fmt::Result { - fmt.debug_tuple("Indent").field(&self.content).finish() - } -} - -impl Indent { - pub fn new(content: FormatElement) -> Self { - Self { - content: Box::new(content), - } - } -} - /// A token used to gather a list of elements; see [concat_elements] and [join_elements]. -#[derive(Clone, Eq, PartialEq)] +#[derive(Clone, Default, Eq, PartialEq)] pub struct List { content: Vec, } @@ -1309,8 +196,8 @@ impl Deref for List { /// reaches the specified `line_width`. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Fill { - list: List, - separator: FormatElement, + pub(super) list: List, + pub(super) separator: FormatElement, } impl Fill { @@ -1400,14 +287,14 @@ impl BestFitting { /// ## Safety /// The slice must contain at least two variants. #[doc(hidden)] - pub unsafe fn from_slice_unchecked(variants: &[FormatElement]) -> Self { + pub(crate) unsafe fn from_vec_unchecked(variants: Vec) -> Self { debug_assert!( variants.len() >= 2, "Requires at least the least expanded and most expanded variants" ); Self { - variants: Vec::from(variants).into_boxed_slice(), + variants: variants.into_boxed_slice(), } } @@ -1505,60 +392,6 @@ impl Debug for Token { } impl Token { - /// Create a token from a static string - const fn new_static(text: &'static str) -> Self { - Self::Static { text } - } - - /// Create a token from a dynamic string and a range of the input source - pub fn new_dynamic(text: String, position: TextSize) -> Self { - debug_assert_no_newlines(&text); - - Self::Dynamic { - text: text.into_boxed_str(), - source_position: position, - } - } - - /// Creates a token from a [Cow] that is a sub-slice over the text of a token. - /// - /// The `start` is the absolute start of the token in the source text. - /// - /// ## Returns - /// * [Token::Dynamic] if `text` is a [Cow::Owned] (text doesn't match syntax token text) - /// * [Token::SyntaxTokenSlice] if `text` is borrowed. Avoids allocating a new string. - pub fn from_syntax_token_cow_slice( - text: Cow, - token: &SyntaxToken, - start: TextSize, - ) -> Self { - match text { - Cow::Owned(text) => Self::new_dynamic(text, start), - Cow::Borrowed(text) => { - let range = TextRange::at(start, text.text_len()); - debug_assert_eq!( - text, - &token.text()[range - token.text_range().start()], - "The borrowed string doesn't match the specified token substring. Does the borrowed string belong to this token and range?" - ); - Token::new_syntax_token_slice(token, range) - } - } - } - - /// Creates a new [Token] with a text backed by the string of [SyntaxToken] - pub fn new_syntax_token_slice(token: &SyntaxToken, range: TextRange) -> Self { - let relative_range = range - token.text_range().start(); - let slice = token.token_text().slice(relative_range); - - debug_assert_no_newlines(&slice); - - Self::SyntaxTokenSlice { - slice, - source_position: range.start(), - } - } - /// Get the range of the input source covered by this token, /// or None if the token was synthesized by the formatter pub fn source_position(&self) -> Option<&TextSize> { @@ -1574,10 +407,6 @@ impl Token { } } -fn debug_assert_no_newlines(text: &str) { - debug_assert!(!text.contains('\r'), "The content '{}' contains an unsupported '\\r' line terminator character but string tokens must only use line feeds '\\n' as line separator. Use '\\n' instead of '\\r' and '\\r\\n' to insert a line break in strings.", text); -} - // Token equality only compares the text content impl PartialEq for Token { fn eq(&self, other: &Self) -> bool { @@ -1585,20 +414,6 @@ impl PartialEq for Token { } } -impl From> for Token { - fn from(token: SyntaxToken) -> Self { - Self::from(&token) - } -} - -impl<'a, L: Language> From<&'a SyntaxToken> for Token { - fn from(token: &'a SyntaxToken) -> Self { - let trimmed_range = token.text_trimmed_range(); - - Self::new_syntax_token_slice(token, trimmed_range) - } -} - const LINE_SEPARATOR: char = '\u{2028}'; const PARAGRAPH_SEPARATOR: char = '\u{2029}'; pub const LINE_TERMINATORS: [char; 3] = ['\r', LINE_SEPARATOR, PARAGRAPH_SEPARATOR]; @@ -1631,17 +446,6 @@ pub fn normalize_newlines(text: &str, terminators: [char; N]) -> } } -impl From> for Token { - fn from(trivia: SyntaxTriviaPieceComments) -> Self { - let range = trivia.text_range(); - Token::from_syntax_token_cow_slice( - normalize_newlines(trivia.text().trim(), LINE_TERMINATORS), - &trivia.as_piece().token(), - range.start(), - ) - } -} - impl Deref for Token { type Target = str; fn deref(&self) -> &Self::Target { @@ -1657,8 +461,11 @@ impl Deref for Token { impl FormatElement { /// Returns true if the element contains no content. - pub const fn is_empty(&self) -> bool { - matches!(self, FormatElement::Empty) + pub fn is_empty(&self) -> bool { + match self { + FormatElement::List(list) => list.is_empty(), + _ => false, + } } /// Returns true if this [FormatElement] is guaranteed to break across multiple lines by the printer. @@ -1670,10 +477,9 @@ impl FormatElement { /// lines if this element is part of a group and the group doesn't fit on a single line. pub fn will_break(&self) -> bool { match self { - FormatElement::Empty => false, FormatElement::Space => false, - FormatElement::Line(line) => matches!(line.mode, LineMode::Hard | LineMode::Empty), - FormatElement::Indent(indent) => indent.content.will_break(), + FormatElement::Line(line_mode) => matches!(line_mode, LineMode::Hard | LineMode::Empty), + FormatElement::Indent(content) => content.will_break(), FormatElement::Group(group) => group.content.will_break(), FormatElement::ConditionalGroupContent(group) => group.content.will_break(), FormatElement::List(list) => list.content.iter().any(FormatElement::will_break), @@ -1709,7 +515,7 @@ impl FormatElement { (FormatElement::List(list), content) } else { // No leading trivia - (empty_element(), list.content) + (FormatElement::List(List::default()), list.content) }; let content_end = content @@ -1721,17 +527,25 @@ impl FormatElement { let trailing = if trailing_start < content.len() { FormatElement::List(List::new(content.split_off(trailing_start))) } else { - empty_element() + FormatElement::List(List::default()) }; (leading, FormatElement::List(List::new(content)), trailing) } else { // All leading trivia - (FormatElement::List(list), empty_element(), empty_element()) + ( + FormatElement::List(list), + FormatElement::List(List::default()), + FormatElement::List(List::default()), + ) } } // Non-list elements are returned directly - _ => (empty_element(), self, empty_element()), + _ => ( + FormatElement::List(List::default()), + self, + FormatElement::List(List::default()), + ), } } @@ -1748,9 +562,9 @@ impl FormatElement { FormatElement::List(list) => { list.iter().rev().find_map(|element| element.last_element()) } - FormatElement::Empty | FormatElement::Line(_) | FormatElement::Comment(_) => None, + FormatElement::Line(_) | FormatElement::Comment(_) => None, - FormatElement::Indent(indent) => indent.content.last_element(), + FormatElement::Indent(indent) => indent.last_element(), FormatElement::Group(group) => group.content.last_element(), _ => Some(self), @@ -1776,143 +590,35 @@ impl From for FormatElement { } } -impl From for FormatElement { - fn from(token: ConditionalGroupContent) -> Self { - FormatElement::ConditionalGroupContent(token) - } -} +impl FromIterator for FormatElement { + fn from_iter>(iter: T) -> Self { + let iter = iter.into_iter(); -impl From for FormatElement { - fn from(token: Line) -> Self { - FormatElement::Line(token) - } -} + let mut list = Vec::with_capacity(iter.size_hint().0); -impl From for FormatElement { - fn from(token: Indent) -> Self { - FormatElement::Indent(token) + for element in iter { + match element { + FormatElement::List(append) => { + list.extend(append.content); + } + element => list.push(element), + } + } + + FormatElement::from(List::new(list)) } } -impl From> for FormatElement { - fn from(element: Option) -> Self { - element.unwrap_or_else(empty_element) +impl From for FormatElement { + fn from(token: ConditionalGroupContent) -> Self { + FormatElement::ConditionalGroupContent(token) } } #[cfg(test)] mod tests { - use crate::format_element::{ - empty_element, join_elements, normalize_newlines, List, LINE_TERMINATORS, - }; - use crate::{concat_elements, space_token, token, FormatElement}; - - #[test] - fn concat_elements_returns_a_list_token_containing_the_passed_in_elements() { - let concatenated = concat_elements(vec![token("a"), space_token(), token("b")]); - - assert_eq!( - concatenated, - FormatElement::List(List::new(vec![token("a"), space_token(), token("b")])) - ); - } - - #[test] - fn concat_elements_returns_the_passed_in_element_if_the_content_is_a_list_with_a_single_element( - ) { - let concatenated = concat_elements(vec![token("a")]); - - assert_eq!(concatenated, token("a")); - } - - #[test] - fn concat_elements_the_empty_element_if_the_passed_vector_is_empty() { - let concatenated = concat_elements(vec![]); - - assert_eq!(concatenated, empty_element()); - } - - #[test] - fn concat_elements_flattens_sub_lists_and_skips_empty_elements() { - let concatenated = concat_elements(vec![ - token("a"), - space_token(), - empty_element(), - concat_elements(vec![token("1"), space_token(), token("2")]), - space_token(), - token("b"), - ]); - - assert_eq!( - concatenated, - FormatElement::List(List::new(vec![ - token("a"), - space_token(), - token("1"), - space_token(), - token("2"), - space_token(), - token("b") - ])) - ); - } - - #[test] - fn join_elements_inserts_the_separator_between_elements() { - let joined = join_elements(space_token(), vec![token("a"), token("b"), token("c")]); - - assert_eq!( - joined, - concat_elements(vec![ - token("a"), - space_token(), - token("b"), - space_token(), - token("c") - ]) - ); - } - - #[test] - fn join_returns_the_content_element_if_the_content_contains_a_single_element() { - let joined = join_elements(space_token(), vec![token("a")]); - - assert_eq!(joined, token("a")); - } - - #[test] - fn join_returns_the_empty_element_if_the_passed_vec_is_empty() { - let joined = join_elements(space_token(), vec![]); - - assert_eq!(joined, empty_element()); - } - - #[test] - fn join_flattens_sub_lists_and_skips_empty_elements_without_inserting_separators() { - let joined = join_elements( - space_token(), - vec![ - token("a"), - empty_element(), - concat_elements(vec![token("1"), token("+"), token("2")]), - token("b"), - ], - ); - - assert_eq!( - joined, - FormatElement::List(List::new(vec![ - token("a"), - space_token(), - token("1"), - token("+"), - token("2"), - space_token(), - token("b") - ])) - ); - } + use crate::format_element::{normalize_newlines, LINE_TERMINATORS}; #[test] fn test_normalize_newlines() { diff --git a/crates/rome_formatter/src/format_extensions.rs b/crates/rome_formatter/src/format_extensions.rs index bda64ddfc4a..73b4128e79a 100644 --- a/crates/rome_formatter/src/format_extensions.rs +++ b/crates/rome_formatter/src/format_extensions.rs @@ -1,15 +1,15 @@ use crate::prelude::*; use std::cell::RefCell; +use std::marker::PhantomData; -use crate::IntoFormatElement; -use rome_rowan::SyntaxResult; +use crate::{write, Buffer, VecBuffer}; /// Utility trait used to simplify the formatting of optional objects that are formattable. /// /// In order to take advantage of all the functions, you only need to implement the [FormatOptionalTokenAndNode::with_or] /// function. -pub trait FormatOptional { - type Context; +pub trait FormatOptional { + type Target: Format; /// This function tries to format an optional object. If the object is [None] /// an [empty token](crate::FormatElement::Empty) is created. If exists, the utility @@ -18,282 +18,80 @@ pub trait FormatOptional { /// ## Examples /// /// ``` + /// use rome_formatter::{write, format}; /// use rome_formatter::prelude::*; /// use rome_rowan::TextSize; /// /// struct MyFormat; /// - /// impl Format for MyFormat { - /// type Context = (); - /// - /// fn format(&self, formatter: &Formatter) -> FormatResult { - /// Ok(token("MyToken")) + /// impl Format for MyFormat { + /// fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { + /// write!(f, [token("MyToken")]) /// } /// } /// - /// let formatter = Formatter::default(); - /// /// let none_token: Option = None; /// // Returns `empty_element()` for a `None` value - /// let none_result = none_token.with_or_empty(|token| token); - /// assert_eq!(Ok(empty_element()), formatted![&formatter, [none_result]]); - /// - /// let some_token = Some(MyFormat); - /// let some_result = some_token.with_or_empty(|token| { - /// formatted![&formatter, [space_token(), token]] - /// }); - /// assert_eq!(formatted![&formatter, [space_token(), token("MyToken")]], formatted![&formatter, [some_result]]); - fn with_or_empty( - &self, - with: With, - ) -> FormatWithOr FormatElement, WithResult, FormatElement, Self::Context> - where - With: Fn(FormatElement) -> WithResult, - WithResult: IntoFormatElement, - { - self.with_or(with, empty_element) - } - - /// This function tries to format an optional formattable object as is. If the object is [None], - /// it calls the passed closure, which has to return a [crate::FormatElement] - /// - /// ## Examples - /// - /// ``` - /// use rome_formatter::prelude::*; - /// use rome_rowan::TextSize; - /// - /// struct MyFormat; - /// - /// impl Format for MyFormat { - /// type Context = (); - /// fn format(&self, formatter: &Formatter) -> FormatResult { - /// Ok(token("MyToken")) - /// } - /// } - /// - /// let formatter = Formatter::default(); - /// let none_token: Option = None; - /// let result = none_token.or_format(|| token(" other result")); - /// - /// assert_eq!(Ok(token(" other result")), formatted![&formatter, [result]]); - fn or_format(&self, op: Or) -> OrFormat - where - Or: Fn() -> OrResult, - OrResult: IntoFormatElement, - { - self.with_or(|token| token, op) - } - - /// If the object isn't [None], it will call the first closure which will accept formatted element. - /// - /// If the object is [None], the second closure will be called. - /// - /// Both closures have to return a [crate::FormatElement]. This function will make sure to wrap them into [Ok]. - /// - /// ## Examples - /// - /// ``` - /// use rome_formatter::prelude::*; - /// use rome_rowan::TextSize; - /// - /// struct MyFormat; - /// - /// impl Format for MyFormat { - /// type Context = (); - /// fn format(&self, formatter: &Formatter) -> FormatResult { - /// Ok(token("MyToken")) - /// } - /// } - /// - /// let formatter = Formatter::default(); - /// let none_token: Option = None; - /// - /// // It returns the `or` result if called on `None` - /// let none_result = none_token.with_or(|token| token, || { - /// token("empty") - /// }); - /// assert_eq!(Ok(token("empty")), formatted![&formatter, [none_result]]); - /// - /// // Returns the result of the first callback when called with `Some(value)` - /// let some_result = Some(MyFormat).with_or(|token| { - /// formatted![&formatter, [space_token(), token]] - /// }, || empty_element()); - /// - /// assert_eq!(formatted![&formatter, [space_token(), token("MyToken")]], formatted![&formatter, [some_result]]); - fn with_or( - &self, - with: With, - op: Or, - ) -> FormatWithOr - where - With: Fn(FormatElement) -> WithResult, - WithResult: IntoFormatElement, - Or: Fn() -> OrResult, - OrResult: IntoFormatElement; -} - -/// Utility trait for formatting a formattable object with some additional content. -pub trait FormatWith: Format { - /// Allows to chain a formattable object with another [elements](FormatElement) - /// - /// The function will decorate the result with [Ok] - /// - /// The formatted element is passed to the closure, which then can appended to additional elements. - /// This method is useful in case, for example, a token has to be chained with a space. - /// - /// ## Examples - /// - /// ``` - /// use rome_formatter::prelude::*; - /// use rome_rowan::TextSize; + /// let none_formatted = format!(SimpleFormatContext::default(), [ + /// none_token.with_or_empty(|token, f| write!(f, [token])) + /// ]).unwrap(); /// - /// struct MyFormat; - /// - /// impl Format for MyFormat { - /// type Context = (); - /// fn format(&self, formatter: &Formatter) -> FormatResult { - /// Ok(token("MyToken")) - /// } - /// } + /// assert!(none_formatted.into_format_element().is_empty()); /// - /// let formatter = Formatter::default(); - /// - /// let result = MyFormat.with(|string_literal| { - /// formatted![&formatter, [string_literal, space_token(), token("+")]] - /// }); - /// - /// assert_eq!(formatted![&formatter, [token("MyToken"), space_token(), token("+")]], formatted![&formatter, [result]]) - fn with(&self, with: With) -> FormatItemWith + /// let some_token = Some(MyFormat); + /// assert_eq!( + /// format![SimpleFormatContext::default(), [space_token(), token("MyToken")]], + /// format!( + /// SimpleFormatContext::default(), [ + /// some_token.with_or_empty(|token, f| { + /// write!(f, [space_token(), token]) + /// }) + /// ] + /// ) + /// ); + fn with_or_empty(self, with: With) -> Option> where - With: Fn(FormatElement) -> WithResult, - WithResult: IntoFormatElement; + With: Fn(&Self::Target, &mut Formatter) -> FormatResult<()>; } -pub struct FormatItemWith<'a, With, WithResult, Context> -where - With: Fn(FormatElement) -> WithResult, - WithResult: IntoFormatElement, -{ +#[derive(Copy, Clone, Debug)] +pub struct FormatItemWith { with: With, - inner: &'a dyn Format, + inner: Format, } -impl<'a, With, WithResult, Context> Format for FormatItemWith<'a, With, WithResult, Context> +impl Format for FormatItemWith where - With: Fn(FormatElement) -> WithResult, - WithResult: IntoFormatElement, + F: Format, + With: Fn(&F, &mut Formatter) -> FormatResult<()>, { - type Context = Context; - - fn format(&self, formatter: &Formatter) -> FormatResult { - let element = self.inner.format(formatter)?; - - (self.with)(element).into_format_element(formatter) - } -} - -impl FormatWith for F { - fn with(&self, with: With) -> FormatItemWith - where - With: Fn(FormatElement) -> WithResult, - WithResult: IntoFormatElement, - { - FormatItemWith { with, inner: self } - } -} - -impl FormatOptional for SyntaxResult> { - type Context = F::Context; - - fn with_or( - &self, - with: With, - op: Or, - ) -> FormatWithOr - where - With: Fn(FormatElement) -> WithResult, - WithResult: IntoFormatElement, - Or: Fn() -> OrResult, - OrResult: IntoFormatElement, - { - match self { - Err(_) => FormatWithOr::With { inner: self, with }, - Ok(Some(value)) => FormatWithOr::With { inner: value, with }, - Ok(None) => FormatWithOr::Or(op), - } + fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { + (self.with)(&self.inner, f) } } -impl FormatOptional for Option { - type Context = F::Context; +impl, Context> FormatOptional for Option { + type Target = F; - fn with_or( - &self, - with: With, - op: Or, - ) -> FormatWithOr + #[inline] + fn with_or_empty(self, with: With) -> Option> where - With: Fn(FormatElement) -> WithResult, - WithResult: IntoFormatElement, - Or: Fn() -> OrResult, - OrResult: IntoFormatElement, + With: Fn(&F, &mut Formatter) -> FormatResult<()>, { - match self { - None => FormatWithOr::Or(op), - Some(value) => FormatWithOr::With { inner: value, with }, - } - } -} - -pub type OrFormat<'a, Or, OrResult, Context> = - FormatWithOr<'a, fn(FormatElement) -> FormatElement, Or, FormatElement, OrResult, Context>; - -pub enum FormatWithOr<'a, With, Or, WithResult, OrResult, Context> -where - With: Fn(FormatElement) -> WithResult, - Or: Fn() -> OrResult, - WithResult: IntoFormatElement, - OrResult: IntoFormatElement, -{ - With { - inner: &'a dyn Format, - with: With, - }, - Or(Or), -} - -impl<'a, With, Or, WithResult, OrResult, Context> Format - for FormatWithOr<'a, With, Or, WithResult, OrResult, Context> -where - With: Fn(FormatElement) -> WithResult, - Or: Fn() -> OrResult, - WithResult: IntoFormatElement, - OrResult: IntoFormatElement, -{ - type Context = Context; - - #[inline] - fn format(&self, formatter: &Formatter) -> FormatResult { - match self { - FormatWithOr::Or(op) => op().into_format_element(formatter), - FormatWithOr::With { inner, with } => { - with(inner.format(formatter)?).into_format_element(formatter) - } - } + self.map(|value| FormatItemWith { inner: value, with }) } } /// Utility trait that allows memorizing the output of a [Format]. /// Useful to avoid re-formatting the same object twice. -pub trait MemoizeFormat { +pub trait MemoizeFormat { /// Returns a formattable object that memoizes the result of `Format` by cloning. /// Mainly useful if the same sub-tree can appear twice in the formatted output because it's /// used inside of `if_group_breaks` or `if_group_fits_single_line`. /// /// ``` /// use std::cell::Cell; - /// use rome_formatter::FormatContext; + /// use rome_formatter::{format, write}; /// use rome_formatter::prelude::*; /// use rome_rowan::TextSize; /// @@ -307,72 +105,98 @@ pub trait MemoizeFormat { /// } /// } /// - /// impl Format for MyFormat { - /// type Context = (); - /// fn format(&self, formatter: &Formatter) -> FormatResult { + /// impl Format for MyFormat { + /// fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { /// let value = self.value.get(); /// self.value.set(value + 1); /// - /// Ok(FormatElement::from(Token::new_dynamic(format!("Formatted {value} times."), TextSize::from(0)))) + /// write!(f, [dynamic_token(&std::format!("Formatted {value} times."), TextSize::from(0))]) /// } /// } /// - /// let formatter = Formatter::default(); /// let normal = MyFormat::new(); /// /// // Calls `format` for everytime the object gets formatted /// assert_eq!( - /// Ok(format_elements![token("Formatted 1 times."), token("Formatted 2 times.")]), - /// formatted![&formatter, [&normal, &normal]] + /// format!(SimpleFormatContext::default(), [token("Formatted 1 times."), token("Formatted 2 times.")]), + /// format!(SimpleFormatContext::default(), [normal, normal]) /// ); /// /// // Memoized memoizes the result and calls `format` only once. /// let memoized = normal.memoized(); /// assert_eq!( - /// Ok(format_elements![token("Formatted 3 times."), token("Formatted 3 times.")]), - /// formatted![&formatter, [&memoized, &memoized]] + /// format!(SimpleFormatContext::default(), [token("Formatted 3 times."), token("Formatted 3 times.")]), + /// format![SimpleFormatContext::default(), [memoized, memoized]] /// ); /// ``` /// - fn memoized(self) -> Memoized + fn memoized(self) -> Memoized where - Self: Sized + Format, + Self: Sized + Format, { Memoized::new(self) } } -impl MemoizeFormat for F where F: Format {} +impl MemoizeFormat for T where T: Format {} /// Memoizes the output of its inner [Format] to avoid re-formatting a potential expensive object. -pub struct Memoized { +pub struct Memoized { inner: F, - memory: RefCell>>, + memory: RefCell>>>, + options: PhantomData, } -impl Memoized { +impl Memoized +where + F: Format, +{ fn new(inner: F) -> Self { Self { inner, memory: RefCell::new(None), + options: PhantomData, } } } -impl Format for Memoized +impl Format for Memoized where - F: Format, + F: Format, { - type Context = F::Context; - - fn format(&self, formatter: &Formatter) -> FormatResult { + fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { + // Cached if let Some(memory) = self.memory.borrow().as_ref() { - return memory.clone(); + return match memory { + Ok(elements) => { + for element in elements { + f.write_element(element.clone())?; + } + + Ok(()) + } + Err(err) => Err(*err), + }; } + let mut buffer = VecBuffer::new(f.state_mut()); + + let result = write!(buffer, [self.inner]); + + match result { + Ok(_) => { + let elements = buffer.into_vec(); + for element in &elements { + f.write_element(element.clone())?; + } - let formatted = self.inner.format(formatter); - *self.memory.borrow_mut() = Some(formatted.clone()); + *self.memory.borrow_mut() = Some(Ok(elements)); - formatted + Ok(()) + } + Err(err) => { + *self.memory.borrow_mut() = Some(Err(err)); + Err(err) + } + } } } diff --git a/crates/rome_formatter/src/formatter.rs b/crates/rome_formatter/src/formatter.rs index 78de68b631e..9e0eb16905b 100644 --- a/crates/rome_formatter/src/formatter.rs +++ b/crates/rome_formatter/src/formatter.rs @@ -1,113 +1,222 @@ -use crate::group_id::UniqueGroupIdBuilder; +use crate::buffer::BufferSnapshot; +use crate::builders::{FillBuilder, JoinBuilder}; use crate::prelude::*; #[cfg(debug_assertions)] use crate::printed_tokens::PrintedTokens; -use crate::GroupId; -use rome_rowan::{Language, SyntaxNode, SyntaxToken}; -#[cfg(debug_assertions)] -use std::cell::RefCell; +use crate::{Arguments, Buffer, FormatState, GroupId}; -/// Handles the formatting of a CST and stores the options how the CST should be formatted (user preferences). +/// Handles the formatting of a CST and stores the context how the CST should be formatted (user preferences). /// The formatter is passed to the [Format] implementation of every node in the CST so that they /// can use it to format their children. -#[derive(Default)] -pub struct Formatter { - /// Yields various information that belong to the current instance of the formatter - context: Context, - group_id_builder: UniqueGroupIdBuilder, - // This is using a RefCell as it only exists in debug mode, - // the Formatter is still completely immutable in release builds - #[cfg(debug_assertions)] - pub printed_tokens: RefCell, +pub struct Formatter<'buf, Context> { + pub(super) buffer: &'buf mut dyn Buffer, } -impl Formatter { - /// Creates a new context that uses the given formatter options - pub fn new(options: Context) -> Self { - Self { - context: options, - group_id_builder: Default::default(), - #[cfg(debug_assertions)] - printed_tokens: Default::default(), - } +impl<'buf, Context> Formatter<'buf, Context> { + /// Creates a new context that uses the given formatter context + pub fn new(buffer: &'buf mut (dyn Buffer + 'buf)) -> Self { + Self { buffer } } - /// Returns the [FormatOptions] specifying how to format the current CST + /// Returns the Context specifying how to format the current CST pub fn context(&self) -> &Context { - &self.context + self.state().context() } /// Creates a new group id that is unique to this document. The passed debug name is used in the /// [std::fmt::Debug] of the document if this is a debug build. /// The name is unused for production builds and has no meaning on the equality of two group ids. pub fn group_id(&self, debug_name: &'static str) -> GroupId { - self.group_id_builder.group_id(debug_name) + self.state().group_id(debug_name) } - /// Tracks the given token as formatted - #[inline] - pub fn track_token(&self, #[allow(unused_variables)] token: &SyntaxToken) { - cfg_if::cfg_if! { - if #[cfg(debug_assertions)] { - self.printed_tokens.borrow_mut().track_token(token); - } - } + /// Joins multiple [Format] together without any separator + /// + /// ## Examples + /// + /// ```rust + /// use rome_formatter::format; + /// use rome_formatter::prelude::*; + /// + /// let formatted = format!(SimpleFormatContext::default(), [format_with(|f| { + /// f.join() + /// .entry(&token("a")) + /// .entry(&space_token()) + /// .entry(&token("+")) + /// .entry(&space_token()) + /// .entry(&token("b")) + /// .finish() + /// })]).unwrap(); + /// + /// assert_eq!( + /// "a + b", + /// formatted.print().as_code() + /// ) + /// ``` + pub fn join<'a>(&'a mut self) -> JoinBuilder<'a, 'buf, (), Context> { + JoinBuilder::new(self) } - #[inline] - pub fn assert_formatted_all_tokens( - &self, - #[allow(unused_variables)] root: &SyntaxNode, - ) { - cfg_if::cfg_if! { - if #[cfg(debug_assertions)] { - let printed_tokens = self.printed_tokens.borrow(); - printed_tokens.assert_all_tracked(root); - } - } + /// Joins the objects by placing the specified separator between every two items. + /// + /// ## Examples + /// + /// Joining different tokens by separating them with a comma and a space. + /// + /// ``` + /// use rome_formatter::{format, format_args}; + /// use rome_formatter::prelude::*; + /// + /// let formatted = format!(SimpleFormatContext::default(), [format_with(|f| { + /// f.join_with(&format_args!(token(","), space_token())) + /// .entry(&token("1")) + /// .entry(&token("2")) + /// .entry(&token("3")) + /// .entry(&token("4")) + /// .finish() + /// })]).unwrap(); + /// + /// assert_eq!( + /// "1, 2, 3, 4", + /// formatted.print().as_code() + /// ); + /// ``` + pub fn join_with<'a, Joiner>( + &'a mut self, + joiner: Joiner, + ) -> JoinBuilder<'a, 'buf, Joiner, Context> + where + Joiner: Format, + { + JoinBuilder::with_separator(self, joiner) } - /// Formats all items of the iterator and returns the formatted result + /// Specialized version of [join_with] for joining SyntaxNodes separated by a space, soft + /// line break or empty line depending on the input file. /// - /// Returns the [Err] of the first item that failed to format. - #[inline] - pub fn format_all>( - &self, - nodes: impl IntoIterator, - ) -> FormatResult> { - let mut result = Vec::new(); - - for node in nodes { - match node.format(self) { - Ok(formatted) => { - result.push(formatted); - } - Err(err) => return Err(err), - } - } + /// This functions inspects the input source and separates consecutive elements with either + /// a [soft_line_break_or_space] or [empty_line] depending on how many line breaks were + /// separating the elements in the original file. + pub fn join_nodes_with_soft_line<'a>( + &'a mut self, + ) -> JoinNodesBuilder<'a, 'buf, Line, Context> { + JoinNodesBuilder::new(soft_line_break_or_space(), self) + } - Ok(result.into_iter()) + /// Specialized version of [join_with] for joining SyntaxNodes separated by one or more + /// line breaks depending on the input file. + /// + /// This functions inspects the input source and separates consecutive elements with either + /// a [hard_line_break] or [empty_line] depending on how many line breaks were separating the + /// elements in the original file. + pub fn join_nodes_with_hardline<'a>(&'a mut self) -> JoinNodesBuilder<'a, 'buf, Line, Context> { + JoinNodesBuilder::new(hard_line_break(), self) + } + + /// Concatenates a list of [Format] objects with spaces and line breaks to fit + /// them on as few lines as possible. Each element introduces a conceptual group. The printer + /// first tries to print the item in flat mode but then prints it in expanded mode if it doesn't fit. + /// + /// ## Examples + /// + /// ```rust + /// use rome_formatter::prelude::*; + /// use rome_formatter::{format, format_args}; + /// + /// let formatted = format!(SimpleFormatContext::default(), [format_with(|f| { + /// f.fill(soft_line_break_or_space()) + /// .entry(&token("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")) + /// .entry(&token("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")) + /// .entry(&token("cccccccccccccccccccccccccccccc")) + /// .entry(&token("dddddddddddddddddddddddddddddd")) + /// .finish() + /// })]).unwrap(); + /// + /// assert_eq!( + /// "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\ncccccccccccccccccccccccccccccc dddddddddddddddddddddddddddddd", + /// formatted.print().as_code() + /// ) + /// ``` + /// + /// ```rust + /// use rome_formatter::prelude::*; + /// use rome_formatter::{format, format_args}; + /// + /// let entries = vec![ + /// token("Important: "), + /// token("Please do not commit memory bugs such as segfaults, buffer overflows, etc. otherwise you "), + /// token("will"), + /// token(" be reprimanded") + /// ]; + /// + /// let formatted = format!(SimpleFormatContext::default(), [format_with(|f| { + /// f.fill(soft_line_break()).entries(entries.iter()).finish() + /// })]).unwrap(); + /// + /// assert_eq!( + /// &std::format!("Important: \nPlease do not commit memory bugs such as segfaults, buffer overflows, etc. otherwise you \nwill be reprimanded"), + /// formatted.print().as_code() + /// ) + /// ``` + pub fn fill<'a, Separator>(&'a mut self, separator: Separator) -> FillBuilder<'a, 'buf, Context> + where + Separator: Format, + { + FillBuilder::new(self, separator) } } -impl Formatter { +impl Formatter<'_, Context> { /// Take a snapshot of the state of the formatter #[inline] pub fn snapshot(&self) -> FormatterSnapshot { FormatterSnapshot { + buffer: self.buffer.snapshot(), #[cfg(debug_assertions)] - printed_tokens: self.printed_tokens.borrow().clone(), + printed_tokens: self.state().printed_tokens.clone(), } } #[inline] /// Restore the state of the formatter to a previous snapshot - pub fn restore(&self, #[allow(unused)] snapshot: FormatterSnapshot) { + pub fn restore_snapshot(&mut self, snapshot: FormatterSnapshot) { cfg_if::cfg_if! { if #[cfg(debug_assertions)] { - *self.printed_tokens.borrow_mut() = snapshot.printed_tokens; + self.state_mut().printed_tokens = snapshot.printed_tokens; } } + self.buffer.restore_snapshot(snapshot.buffer) + } +} + +impl Buffer for Formatter<'_, Context> { + type Context = Context; + + fn write_element(&mut self, element: FormatElement) -> FormatResult<()> { + self.buffer.write_element(element) + } + + fn write_fmt(&mut self, arguments: Arguments) -> FormatResult<()> { + for argument in arguments.items() { + argument.format(self)?; + } + Ok(()) + } + + fn state(&self) -> &FormatState { + self.buffer.state() + } + + fn state_mut(&mut self) -> &mut FormatState { + self.buffer.state_mut() + } + + fn snapshot(&self) -> BufferSnapshot { + self.buffer.snapshot() + } + + fn restore_snapshot(&mut self, snapshot: BufferSnapshot) { + self.buffer.restore_snapshot(snapshot) } } @@ -118,6 +227,7 @@ impl Formatter { /// In practice this only saves the set of printed tokens in debug /// mode and compiled to nothing in release mode pub struct FormatterSnapshot { + buffer: BufferSnapshot, #[cfg(debug_assertions)] printed_tokens: PrintedTokens, } diff --git a/crates/rome_formatter/src/intersperse.rs b/crates/rome_formatter/src/intersperse.rs index b327f5648aa..d385ee12bc1 100644 --- a/crates/rome_formatter/src/intersperse.rs +++ b/crates/rome_formatter/src/intersperse.rs @@ -2,8 +2,6 @@ use std::{fmt::Debug, iter::Peekable}; -use crate::prelude::*; - /// An iterator adapter that places a separator between all elements. #[derive(Debug, Clone)] pub struct Intersperse @@ -80,73 +78,3 @@ where }) } } - -/// An iterator adapter that places a separator between all elements. -/// The separator element is generated by a factory function called -/// by the iterator with the previous and next SyntaxNode as arguments -#[derive(Debug, Clone)] -pub struct IntersperseFn -where - I: Iterator, -{ - separator_factory: F, - iter: Peekable, - prev_item: Option, -} - -impl IntersperseFn -where - I: Iterator, - F: FnMut(&N, &N, &FormatElement) -> FormatElement, -{ - pub fn new(iter: I, separator_factory: F) -> Self { - Self { - iter: iter.peekable(), - separator_factory, - prev_item: None, - } - } -} - -impl Iterator for IntersperseFn -where - I: Iterator, - F: FnMut(&N, &N, &FormatElement) -> FormatElement, -{ - type Item = FormatElement; - - #[inline] - fn next(&mut self) -> Option { - if let Some(prev_node) = self.prev_item.take() { - if let Some((next_node, next_elem)) = self.iter.peek() { - return Some((self.separator_factory)(&prev_node, next_node, next_elem)); - } - } - - match self.iter.next() { - Some((node, elem)) => { - self.prev_item = Some(node); - Some(elem) - } - None => None, - } - } - - fn size_hint(&self) -> (usize, Option) { - let (lo, hi) = self.iter.size_hint(); - let next_is_elem = self.prev_item.is_none(); - let lo = lo.saturating_sub(next_is_elem as usize).saturating_add(lo); - let hi = match hi { - Some(hi) => hi.saturating_sub(next_is_elem as usize).checked_add(hi), - None => None, - }; - (lo, hi) - } -} - -impl ExactSizeIterator for IntersperseFn -where - I: Iterator, - F: FnMut(&N, &N, &FormatElement) -> FormatElement, -{ -} diff --git a/crates/rome_formatter/src/lib.rs b/crates/rome_formatter/src/lib.rs index 6fae7ffdc34..14e8a9cb679 100644 --- a/crates/rome_formatter/src/lib.rs +++ b/crates/rome_formatter/src/lib.rs @@ -6,9 +6,6 @@ //! ## Formatting Traits //! //! * [Format]: Implemented by objects that can be formatted. -//! * [IntoFormatElement]: The arguments passed to the `formatted[formatter, arg1, arg2]` must implement the. -//! [IntoFormatElement] trait. Its main difference to the [Format] trait is that it consumes self rather than borrowing it. -//! This module provides [IntoFormatElement] implementations for every object implementing [Format] and [FormatElement]. //! * [FormatRule]: Rule that knows how to format an object of another type. Necessary in the situation where //! it's necessary to implement [Format] on an object from another crate. This module defines the //! [FormatRefWithRule] and [FormatOwnedWithRule] structs to pass an item with its corresponding rule. @@ -17,12 +14,15 @@ //! //! ## Formatting Macros //! -//! This trait defines two macros to construct the IR. -//! * [format_elements]: Allows concatenating multiple [FormatElement]s -//! * [formatted]: Concatenates a sequence of [FormatElement]s and/or objects implementing [Format]. +//! This crate defines two macros to construct the IR. These are inspired by Rust's `fmt` macros +//! * [`format!`]: Formats a formatable object +//! * [`format_args!`]: Concatenates a sequence of Format objects. +//! * [`write!`]: Writes a sequence of formatable objects into an output buffer. extern crate core; +mod arguments; +mod buffer; mod builders; pub mod format_element; mod format_extensions; @@ -36,20 +36,25 @@ pub mod printed_tokens; pub mod printer; use crate::formatter::Formatter; +use crate::group_id::UniqueGroupIdBuilder; +use crate::prelude::syntax_token_cow_slice; + +#[cfg(debug_assertions)] +use crate::printed_tokens::PrintedTokens; use crate::printer::{Printer, PrinterOptions}; -pub use builders::ConcatBuilder; -pub use format_element::{ - block_indent, comment, concat_elements, empty_element, empty_line, fill_elements, - group_elements, hard_line_break, if_group_breaks, if_group_fits_on_single_line, indent, - join_elements, join_elements_hard_line, join_elements_soft_line, join_elements_with, - line_suffix, normalize_newlines, soft_block_indent, soft_line_break, soft_line_break_or_space, - soft_line_indent_or_space, space_token, token, FormatElement, Token, Verbatim, - LINE_TERMINATORS, +pub use arguments::{Argument, Arguments}; +pub use buffer::{Buffer, BufferExtensions, BufferSnapshot, Inspect, PreambleBuffer, VecBuffer}; +pub use builders::{ + block_indent, comment, empty_element, empty_line, group_elements, hard_line_break, + if_group_breaks, if_group_fits_on_line, indent, line_suffix, soft_block_indent, + soft_line_break, soft_line_break_or_space, soft_line_indent_or_space, space_token, token, + BestFitting, }; +pub use format_element::{normalize_newlines, FormatElement, Token, Verbatim, LINE_TERMINATORS}; pub use group_id::GroupId; use rome_rowan::{ - Language, SyntaxElement, SyntaxError, SyntaxNode, SyntaxResult, TextRange, TextSize, - TokenAtOffset, + Language, SyntaxElement, SyntaxError, SyntaxNode, SyntaxResult, SyntaxToken, + SyntaxTriviaPieceComments, TextRange, TextSize, TokenAtOffset, }; use std::error::Error; use std::fmt; @@ -88,11 +93,11 @@ impl FromStr for IndentStyle { } } -impl fmt::Display for IndentStyle { +impl std::fmt::Display for IndentStyle { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - IndentStyle::Tab => write!(f, "Tab"), - IndentStyle::Space(size) => write!(f, "Spaces, size: {}", size), + IndentStyle::Tab => std::write!(f, "Tab"), + IndentStyle::Space(size) => std::write!(f, "Spaces, size: {}", size), } } } @@ -128,9 +133,9 @@ pub enum ParseLineWidthError { TryFromIntError(LineWidthFromIntError), } -impl fmt::Display for ParseLineWidthError { - fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(fmt, "{self:?}") +impl std::fmt::Display for ParseLineWidthError { + fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + std::write!(fmt, "{self:?}") } } @@ -175,12 +180,34 @@ pub trait FormatContext { fn indent_style(&self) -> IndentStyle; /// What's the max width of a line. Defaults to 80. - fn line_with(&self) -> LineWidth; + fn line_width(&self) -> LineWidth; /// Derives the print options from the these format options fn as_print_options(&self) -> PrinterOptions; } +#[derive(Debug, Default)] +pub struct SimpleFormatContext { + pub indent_style: IndentStyle, + pub line_width: LineWidth, +} + +impl FormatContext for SimpleFormatContext { + fn indent_style(&self) -> IndentStyle { + self.indent_style + } + + fn line_width(&self) -> LineWidth { + self.line_width + } + + fn as_print_options(&self) -> PrinterOptions { + PrinterOptions::default() + .with_indent(self.indent_style) + .with_print_width(self.line_width) + } +} + /// Lightweight sourcemap marker between source and output tokens #[derive(Debug, Clone, Eq, PartialEq)] pub struct SourceMarker { @@ -190,7 +217,7 @@ pub struct SourceMarker { pub dest: TextSize, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Eq, PartialEq)] pub struct Formatted { root: FormatElement, options: PrinterOptions, @@ -305,7 +332,7 @@ pub enum FormatError { } impl fmt::Display for FormatError { - fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { + fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { FormatError::MissingRequiredChild => fmt.write_str("missing required child"), FormatError::UnsupportedLanguage => fmt.write_str("language is not supported"), @@ -337,135 +364,79 @@ impl From<&SyntaxError> for FormatError { /// Implementing `Format` for a custom struct /// /// ``` -/// use rome_formatter::{format, FormatContext, IndentStyle, LineWidth}; +/// use rome_formatter::{format, write, IndentStyle, LineWidth}; /// use rome_formatter::prelude::*; /// use rome_rowan::TextSize; /// /// struct Paragraph(String); /// -/// impl Format for Paragraph { -/// type Context = Context; -/// -/// fn format(&self, formatter: &Formatter) -> FormatResult { -/// formatted![ -/// formatter, -/// [ -/// hard_line_break(), -/// FormatElement::from(Token::new_dynamic(self.0.clone(), TextSize::from(0))), -/// hard_line_break(), -/// ] -/// ] -/// } -/// } -/// -/// struct Context; -/// -/// impl FormatContext for Context { -/// fn indent_style(&self) -> IndentStyle { -/// IndentStyle::Tab -/// } -/// -/// fn line_with(&self) -> LineWidth { -/// LineWidth::default() -/// } -/// -/// fn as_print_options(&self) -> PrinterOptions { -/// PrinterOptions::default() +/// impl Format for Paragraph { +/// fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { +/// write!(f, [ +/// hard_line_break(), +/// dynamic_token(&self.0, TextSize::from(0)), +/// hard_line_break(), +/// ]) /// } /// } /// /// let paragraph = Paragraph(String::from("test")); -/// let printed = format(Context, ¶graph).unwrap().print(); +/// let formatted = format!(SimpleFormatContext::default(), [paragraph]).unwrap(); /// -/// assert_eq!("test\n", printed.as_code()) +/// assert_eq!("test\n", formatted.print().as_code()) /// ``` -pub trait Format { - /// Type of the formatter options. - type Context; - - /// Formats the object - fn format(&self, formatter: &Formatter) -> FormatResult; +pub trait Format { + /// Formats the object using the given formatter. + fn fmt(&self, f: &mut Formatter) -> FormatResult<()>; } -impl Format for &T +impl Format for &T where - T: ?Sized + Format, + T: ?Sized + Format, { - type Context = T::Context; - - fn format(&self, formatter: &Formatter) -> FormatResult { - Format::format(&**self, formatter) + fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { + Format::fmt(&**self, f) } } -impl Format for &mut T +impl Format for &mut T where - T: ?Sized + Format, + T: ?Sized + Format, { - type Context = T::Context; - - fn format(&self, formatter: &Formatter) -> FormatResult { - Format::format(&**self, formatter) + fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { + Format::fmt(&**self, f) } } -impl Format for Option +impl Format for Option where - T: Format, + T: Format, { - type Context = T::Context; - - fn format(&self, formatter: &Formatter) -> FormatResult { + fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { match self { - Some(value) => value.format(formatter), - None => Ok(empty_element()), + Some(value) => value.fmt(f), + None => Ok(()), } } } -impl Format for SyntaxResult +impl Format for SyntaxResult where - T: Format, + T: Format, { - type Context = T::Context; - - fn format(&self, formatter: &Formatter) -> FormatResult { + fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { match self { - Ok(value) => value.format(formatter), + Ok(value) => value.fmt(f), Err(err) => Err(err.into()), } } } -/// Implemented by traits that can be converted to a `FormatElement`. -/// -/// This is similar to [Format] but with the difference that it consumes `self`, allowing it to also -/// be implemented on [FormatElement].format_elements.rs -pub trait IntoFormatElement { - fn into_format_element(self, formatter: &Formatter) -> FormatResult; -} - -impl IntoFormatElement for FormatElement { +impl Format for () { #[inline] - fn into_format_element(self, _: &Formatter) -> FormatResult { - Ok(self) - } -} - -impl IntoFormatElement for FormatResult { - #[inline] - fn into_format_element(self, _: &Formatter) -> FormatResult { - self - } -} - -impl IntoFormatElement for T -where - T: Format, -{ - #[inline] - fn into_format_element(self, formatter: &Formatter) -> FormatResult { - self.format(formatter) + fn fmt(&self, _: &mut Formatter) -> FormatResult<()> { + // Intentionally left empty + Ok(()) } } @@ -482,7 +453,7 @@ where pub trait FormatRule { type Context; - fn format(item: &T, formatter: &Formatter) -> FormatResult; + fn fmt(item: &T, f: &mut Formatter) -> FormatResult<()>; } /// Trait for an object that formats an object with a specified rule. @@ -500,19 +471,17 @@ pub trait FormatRule { /// /// ``` /// use rome_formatter::prelude::*; -/// use rome_formatter::{FormatContext, FormatWithRule}; +/// use rome_formatter::{format, Formatted, FormatWithRule}; /// use rome_rowan::{Language, SyntaxNode}; -/// fn format_node, Context=()>>(node: F) -> FormatResult { -/// let formatter = Formatter::default(); -/// -/// let formatted = node.format(&formatter); +/// fn format_node>>(node: F) -> FormatResult { +/// let formatted = format!(SimpleFormatContext::default(), [node]); /// let _syntax = node.item(); /// /// // Do something with syntax /// formatted /// } /// ``` -pub trait FormatWithRule: Format { +pub trait FormatWithRule: Format { type Item; /// Returns the associated item @@ -540,7 +509,7 @@ where } } -impl FormatWithRule for FormatRefWithRule<'_, T, R> +impl FormatWithRule for FormatRefWithRule<'_, T, R> where R: FormatRule, { @@ -551,15 +520,13 @@ where } } -impl Format for FormatRefWithRule<'_, T, R> +impl Format for FormatRefWithRule<'_, T, R> where R: FormatRule, { - type Context = R::Context; - #[inline] - fn format(&self, formatter: &Formatter) -> FormatResult { - R::format(self.item, formatter) + fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { + R::fmt(self.item, f) } } @@ -593,19 +560,17 @@ where } } -impl Format for FormatOwnedWithRule +impl Format for FormatOwnedWithRule where R: FormatRule, { - type Context = R::Context; - #[inline] - fn format(&self, formatter: &Formatter) -> FormatResult { - R::format(&self.item, formatter) + fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { + R::fmt(&self.item, f) } } -impl FormatWithRule for FormatOwnedWithRule +impl FormatWithRule for FormatOwnedWithRule where R: FormatRule, { @@ -616,18 +581,89 @@ where } } -/// Formats any value that implements [Format]. +/// The `write` function takes a target buffer and an `Arguments` struct that can be precompiled with the `format_args!` macro. /// -/// Please note that [format_node] is preferred to format a [JsSyntaxNode] -pub fn format( - options: C, - root: &dyn Format, -) -> FormatResult { - tracing::trace_span!("format").in_scope(move || { - let printer_options = options.as_print_options(); - let formatter = Formatter::new(options); - let element = root.format(&formatter)?; - Ok(Formatted::new(element, printer_options)) +/// The arguments will be formatted in-order into the output buffer provided. +/// +/// # Examples +/// +/// ``` +/// use rome_formatter::prelude::*; +/// use rome_formatter::{VecBuffer, format_args, FormatState, write, Formatted}; +/// +/// let mut state = FormatState::new(SimpleFormatContext::default()); +/// let mut buffer = VecBuffer::new(&mut state); +/// +/// write(&mut buffer, format_args!(token("Hello World"))).unwrap(); +/// +/// let formatted = Formatted::new(buffer.into_element(), PrinterOptions::default()); +/// +/// assert_eq!("Hello World", formatted.print().as_code()) +/// ``` +/// +/// Please note that using [`write!`] might be preferable. Example: +/// +/// ``` +/// use rome_formatter::prelude::*; +/// use rome_formatter::{VecBuffer, format_args, FormatState, write, Formatted}; +/// +/// let mut state = FormatState::new(SimpleFormatContext::default()); +/// let mut buffer = VecBuffer::new(&mut state); +/// +/// write!(&mut buffer, [token("Hello World")]).unwrap(); +/// +/// let formatted = Formatted::new(buffer.into_element(), PrinterOptions::default()); +/// +/// assert_eq!("Hello World", formatted.print().as_code()) +/// ``` +/// +pub fn write( + output: &mut dyn Buffer, + args: Arguments, +) -> FormatResult<()> { + let mut f = Formatter::new(output); + + f.write_fmt(args) +} + +/// The `format` function takes an [`Arguments`] struct and returns the resulting formatting IR. +/// +/// The [`Arguments`] instance can be created with the [`format_args!`]. +/// +/// # Examples +/// +/// Basic usage: +/// +/// ``` +/// use rome_formatter::prelude::*; +/// use rome_formatter::{format, format_args}; +/// +/// let formatted = format(SimpleFormatContext::default(), format_args!(token("test"))).unwrap(); +/// assert_eq!("test", formatted.print().as_code()); +/// ``` +/// +/// Please note that using [`format!`] might be preferable. Example: +/// +/// ``` +/// use rome_formatter::prelude::*; +/// use rome_formatter::{format}; +/// +/// let formatted = format!(SimpleFormatContext::default(), [token("test")]).unwrap(); +/// assert_eq!("test", formatted.print().as_code()); +/// ``` +pub fn format(context: Context, arguments: Arguments) -> FormatResult +where + Context: FormatContext, +{ + let print_options = context.as_print_options(); + let mut state = FormatState::new(context); + let mut buffer = VecBuffer::with_capacity(arguments.items().len(), &mut state); + + buffer.write_fmt(arguments)?; + + Ok(Formatted { + root: buffer.into_element(), + options: print_options, }) } @@ -635,21 +671,25 @@ pub fn format( /// /// It returns a [Formatted] result, which the user can use to override a file. pub fn format_node< - C: FormatContext, + Context: FormatContext, L: Language, - N: FormatWithRule, Context = C>, + N: FormatWithRule>, >( - options: C, + context: Context, root: &N, ) -> FormatResult { tracing::trace_span!("format_node").in_scope(move || { - let printer_options = options.as_print_options(); - let formatter = Formatter::new(options); - let element = formatted![&formatter, [root]]?; + let print_options = context.as_print_options(); + let mut state = FormatState::new(context); + let mut buffer = VecBuffer::new(&mut state); + + write!(&mut buffer, [root])?; - formatter.assert_formatted_all_tokens(root.item()); + let document = buffer.into_element(); - Ok(Formatted::new(element, printer_options)) + state.assert_formatted_all_tokens(root.item()); + + Ok(Formatted::new(document, print_options)) }) } @@ -709,7 +749,7 @@ where /// It returns a [Formatted] result with a range corresponding to the /// range of the input that was effectively overwritten by the formatter pub fn format_range( - options: Context, + context: Context, root: &SyntaxNode, mut range: TextRange, mut predicate: P, @@ -859,7 +899,7 @@ where // Perform the actual formatting of the root node with // an appropriate indentation level - let formatted = format_sub_tree(options, &FormatRefWithRule::<_, R>::new(common_root))?; + let formatted = format_sub_tree(context, &FormatRefWithRule::<_, R>::new(common_root))?; // This finds the closest marker to the beginning of the source // starting before or at said starting point, and the closest @@ -941,7 +981,7 @@ where pub fn format_sub_tree< C: FormatContext, L: Language, - N: FormatWithRule, Context = C>, + N: FormatWithRule>, >( context: C, root: &N, @@ -1006,3 +1046,96 @@ pub fn format_sub_tree< verbatim_ranges, )) } + +impl Format for SyntaxTriviaPieceComments { + fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { + let range = self.text_range(); + + write!( + f, + [syntax_token_cow_slice( + normalize_newlines(self.text().trim(), LINE_TERMINATORS), + &self.as_piece().token(), + range.start() + )] + ) + } +} + +/// This structure stores the state that is relevant for the formatting of the whole document. +/// +/// This structure is different from [`Formatter`] in that the formatting infrastructure +/// creates a new [`Formatter`] for every [`write`] call, whereas this structure stays alive +/// for the whole process of formatting a root with [`format`]. +#[derive(Default)] +pub struct FormatState { + context: Context, + group_id_builder: UniqueGroupIdBuilder, + // This is using a RefCell as it only exists in debug mode, + // the Formatter is still completely immutable in release builds + #[cfg(debug_assertions)] + pub printed_tokens: PrintedTokens, +} + +impl fmt::Debug for FormatState +where + Context: fmt::Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("FormatState") + .field("context", &self.context) + .finish() + } +} + +impl FormatState { + /// Creates a new state with the given language specific context + pub fn new(context: Context) -> Self { + Self { + context, + group_id_builder: Default::default(), + #[cfg(debug_assertions)] + printed_tokens: Default::default(), + } + } + + /// Returns the context specifying how to format the current CST + pub fn context(&self) -> &Context { + &self.context + } + + /// Returns a mutable reference to the context + pub fn context_mut(&mut self) -> &mut Context { + &mut self.context + } + + /// Creates a new group id that is unique to this document. The passed debug name is used in the + /// [std::fmt::Debug] of the document if this is a debug build. + /// The name is unused for production builds and has no meaning on the equality of two group ids. + pub fn group_id(&self, debug_name: &'static str) -> GroupId { + self.group_id_builder.group_id(debug_name) + } + + /// Tracks the given token as formatted + #[inline] + pub fn track_token(&mut self, #[allow(unused_variables)] token: &SyntaxToken) { + cfg_if::cfg_if! { + if #[cfg(debug_assertions)] { + self.printed_tokens.track_token(token); + } + } + } + + /// Asserts in debug builds that all tokens have been printed. + #[inline] + pub fn assert_formatted_all_tokens( + &self, + #[allow(unused_variables)] root: &SyntaxNode, + ) { + cfg_if::cfg_if! { + if #[cfg(debug_assertions)] { + self.printed_tokens.assert_all_tracked(root); + } + } + } +} diff --git a/crates/rome_formatter/src/macros.rs b/crates/rome_formatter/src/macros.rs index 6e3865020b6..ca6c7f0bfb3 100644 --- a/crates/rome_formatter/src/macros.rs +++ b/crates/rome_formatter/src/macros.rs @@ -1,167 +1,141 @@ -use crate::prelude::*; -use crate::{ConcatBuilder, IntoFormatElement}; -use std::marker::PhantomData; - -/// The macro `format_elements` is a convenience macro to -/// use when writing a list of tokens that should be at the same level -/// without particular rule. -/// -/// # Examples -/// -/// Let's suppose you need to create tokens for the string `"foo": "bar"`, -/// you would write: -/// -/// ```rust -/// use rome_formatter::prelude::*; +/// Constructs the parameters for other formatting macros. /// -/// let element = format_elements![token("foo:"), space_token(), token("bar")]; -/// ``` +/// This macro functions by taking a list of objects implementing [Format]. It canonicalize the +/// arguments into a single type. /// -/// The macro can be also nested, although the macro needs to be decorated with the token you need. -/// For example, let's try to format following string: +/// This macro produces a value of type [`Arguments`]. This value can be passed to +/// the macros within [`rome_formatter`]. All other formatting macros ([`format!`], +/// [`write!`]) are proxied through this one. This macro avoids heap allocations. /// -/// ```no_rust -/// foo: { bar: lorem } -/// ``` -/// You would write it like the following: +/// You can use the [`Arguments`] value that `format_args!` returns in `Format` contexts +/// as seen below. /// /// ```rust -/// use rome_formatter::{FormatContext, Formatted}; +/// use rome_formatter::{SimpleFormatContext, format, format_args}; /// use rome_formatter::prelude::*; /// -/// let element = format_elements![ -/// token("foo:"), -/// space_token(), -/// token("{"), -/// space_token(), -/// token("bar:"), -/// space_token(), -/// token("lorem"), -/// space_token(), -/// token("}") -/// ]; -/// assert_eq!(r#"foo: { bar: lorem }"#, Formatted::new(element, PrinterOptions::default()).print().as_code()); -/// ``` -/// Or you can also create single element: -/// ``` -/// use rome_formatter::{Formatted, FormatContext}; -/// use rome_formatter::prelude::*; +/// let formatted = format!(SimpleFormatContext::default(), [ +/// format_args!(token("Hello World")) +/// ]).unwrap(); /// -/// use rome_formatter::prelude::*; -/// let element = format_elements![token("single")]; -/// assert_eq!(r#"single"#, Formatted::new(element, PrinterOptions::default()).print().as_code()); +/// assert_eq!("Hello World", formatted.print().as_code()); /// ``` +/// +/// [`Format`]: crate::Format +/// [`Arguments`]: crate::Arguments +/// [`format!`]: crate::format +/// [`write!`]: crate::write #[macro_export] -macro_rules! format_elements { - - // called for things like format_tokens!["hey"] - ($element:expr) => { - { - use $crate::FormatElement; - FormatElement::from($element) - } - }; - - ( $( $element:expr ),+ $(,)?) => {{ - use $crate::{FormatElement, concat_elements}; - concat_elements([ +macro_rules! format_args { + ($($value:expr),+ $(,)?) => { + $crate::Arguments::new(&[ $( - FormatElement::from($element) + $crate::Argument::new(&$value) ),+ ]) - }}; + } } -/// The macro `formatted` is a convenience macro to chain a list of [FormatElement] or objects -/// that implement [IntoFormatElement] (which is implemented by all object implementing [Format]). +/// Writes formatted data into a buffer. /// -/// # Examples +/// This macro accepts a 'buffer' and a list of format arguments. Each argument will be formatted +/// and the result will be passed to the buffer. The writer may be any value with a `write_fmt` method; +/// generally this comes from an implementation of the [`Buffer`] trait. /// -/// Let's suppose you need to create tokens for the string `"foo": "bar"`, -/// you would write: +/// # Examples /// /// ```rust -/// use rome_formatter::FormatContext; /// use rome_formatter::prelude::*; +/// use rome_formatter::{Buffer, FormatState, SimpleFormatContext, VecBuffer, write}; /// -/// struct TestFormat; +/// fn main() -> FormatResult<()> { +/// let mut state = FormatState::new(SimpleFormatContext::default()); +/// let mut buffer = VecBuffer::new(&mut state); +/// write!(&mut buffer, [token("Hello"), space_token()])?; +/// write!(&mut buffer, [token("World")])?; /// -/// impl Format for TestFormat { -/// type Context = (); -/// fn format(&self, _: &Formatter) -> FormatResult { -/// Ok(token("test")) -/// } -/// } -/// -/// let formatter = Formatter::default(); +/// assert_eq!( +/// buffer.into_element(), +/// FormatElement::from_iter([ +/// FormatElement::Token(Token::Static { text: "Hello" }), +/// FormatElement::Space, +/// FormatElement::Token(Token::Static { text: "World" }), +/// ]) +/// ); /// -/// let formatted = formatted![ -/// &formatter, -/// [ -/// token("a"), -/// space_token(), -/// token("simple"), -/// space_token(), -/// TestFormat -/// ] -/// ] -/// .unwrap(); -/// -/// assert_eq!( -/// formatted, -/// concat_elements([ -/// token("a"), -/// space_token(), -/// token("simple"), -/// space_token(), -/// token("test") -/// ]) -/// ); +/// Ok(()) +/// } /// ``` +#[macro_export] +macro_rules! write { + ($dst:expr, [$($arg:expr),+ $(,)?]) => {{ + $dst.write_fmt($crate::format_args!($($arg),+)) + }} +} + +/// Writes formatted data into the given buffer and prints all written elements for a quick and dirty debugging. /// -/// Or you can also create single element: -/// ``` +/// An example: +/// +/// ```rust /// use rome_formatter::prelude::*; -/// use rome_formatter::FormatContext; +/// use rome_formatter::{FormatState, VecBuffer}; /// -/// let formatter = Formatter::<()>::default(); +/// let mut state = FormatState::new(SimpleFormatContext::default()); +/// let mut buffer = VecBuffer::new(&mut state); /// -/// let formatted = formatted![&formatter, [token("test")]].unwrap(); +/// dbg_write!(&mut buffer, [token("Hello")]).unwrap(); +/// // ^-- prints: [src/main.rs:7][0] = StaticToken("Hello") /// -/// assert_eq!(formatted, token("test")); +/// assert_eq!(buffer.into_element(), FormatElement::Token(Token::Static { text: "Hello" })); /// ``` +/// +/// Note that the macro is intended as debugging tool and therefore you should avoid having +/// uses of it in version control for long periods (other than in tests and similar). Format output +/// from production code is better done with `[write!]` #[macro_export] -macro_rules! formatted { - - // called for things like formatted![formatter, [token("test")]] - ($formatter:expr, [$element:expr]) => { - { - $crate::IntoFormatElement::into_format_element($element, $formatter) - } - }; - - ($formatter:expr, [$($element:expr),+ $(,)?]) => {{ - use $crate::macros::FormatBuilder; - - const SIZE: usize = $crate::__count_elements!($($element),*); - - let mut builder = FormatBuilder::new(SIZE); - - $( - builder.entry($element, $formatter); - )+ - - builder.finish() - }}; +macro_rules! dbg_write { + ($dst:expr, [$($arg:expr),+ $(,)?]) => {{ + let mut count = 0; + let mut inspect = $crate::Inspect::new($dst, |element: &FormatElement| { + std::eprintln!( + "[{}:{}][{}] = {element:#?}", + std::file!(), std::line!(), count + ); + count += 1; + }); + inspect.write_fmt($crate::format_args!($($arg),+)) + }} } -// Helper macro that counts the count of elements passed -#[doc(hidden)] +/// Creates the Format IR for a value. +/// +/// The first argument `format!` receives is the [FormatContext] that specify how elements must be formatted. +/// Additional parameters passed get formatted by using their [Format] implementation. +/// +/// +/// ## Examples +/// +/// ``` +/// use rome_formatter::prelude::*; +/// use rome_formatter::format; +/// +/// let formatted = format!(SimpleFormatContext::default(), [token("("), token("a"), token(")")]).unwrap(); +/// +/// assert_eq!( +/// formatted.into_format_element(), +/// FormatElement::from_iter([ +/// FormatElement::Token(Token::Static { text: "(" }), +/// FormatElement::Token(Token::Static { text: "a" }), +/// FormatElement::Token(Token::Static { text: ")" }), +/// ]) +/// ); +/// ``` #[macro_export] -macro_rules! __count_elements { - () => {0usize}; - ($ex:expr) => {1usize}; - ($_head:expr, $($tail:expr),* $(,)?) => {1usize + $crate::__count_elements!($($tail),*)}; +macro_rules! format { + ($context:expr, [$($arg:expr),+ $(,)?]) => {{ + ($crate::format($context, $crate::format_args!($($arg),+))) + }} } /// Provides multiple different alternatives and the printer picks the first one that fits. @@ -172,59 +146,64 @@ macro_rules! __count_elements { /// /// ## Examples /// -/// Temporarily ignored because [BestFitting] needs to be adjusted due to the +/// Temporarily ignored because [BestFitting] needs to be adjusted due to the /// `fits_element_on_line` changes in https://github.com/rome/tools/pull/2645 /// ```ignore -/// use rome_formatter::{Formatted, LineWidth}; +/// use rome_formatter::{Formatted, LineWidth, format, format_args}; /// use rome_formatter::prelude::*; /// -/// let elements = format_elements![ -/// token("aVeryLongIdentifier"), -/// best_fitting!( -/// // Everything fits on a single line -/// format_elements![ -/// token("("), -/// group_elements(format_elements![ -/// token("["), -/// soft_block_indent(format_elements![ -/// token("1,"), -/// soft_line_break_or_space(), -/// token("2,"), -/// soft_line_break_or_space(), -/// token("3"), -/// ]), -/// token("]") -/// ]), -/// token(")") -/// ], -/// -/// // Breaks after `[`, but prints all elements on a single line -/// format_elements![ -/// token("("), -/// token("["), -/// block_indent(token("1, 2, 3")), -/// token("]"), -/// token(")"), -/// ], -/// -/// // Breaks after `[` and prints each element on a single line -/// format_elements![ -/// token("("), -/// block_indent(format_elements![ -/// token("["), -/// block_indent(format_elements![ -/// token("1,"), -/// hard_line_break(), -/// token("2,"), -/// hard_line_break(), -/// token("3"), -/// ]), -/// token("]"), -/// ]), -/// token(")") +/// let formatted = format!( +/// SimpleFormatContext::default(), +/// [ +/// token("aVeryLongIdentifier"), +/// best_fitting!( +/// // Everything fits on a single line +/// format_args!( +/// token("("), +/// group_elements(&format_args![ +/// token("["), +/// soft_block_indent(&format_args![ +/// token("1,"), +/// soft_line_break_or_space(), +/// token("2,"), +/// soft_line_break_or_space(), +/// token("3"), +/// ]), +/// token("]") +/// ]), +/// token(")") +/// ), +/// +/// // Breaks after `[`, but prints all elements on a single line +/// format_args!( +/// token("("), +/// token("["), +/// block_indent(&token("1, 2, 3")), +/// token("]"), +/// token(")"), +/// ), +/// +/// // Breaks after `[` and prints each element on a single line +/// format_args!( +/// token("("), +/// block_indent(&format_args![ +/// token("["), +/// block_indent(&format_args![ +/// token("1,"), +/// hard_line_break(), +/// token("2,"), +/// hard_line_break(), +/// token("3"), +/// ]), +/// token("]"), +/// ]), +/// token(")") +/// ) +/// ) /// ] -/// ) -/// ]; +/// ).unwrap(); +/// +/// let elements = formatted.into_format_element(); /// /// // Takes the first variant if everything fits on a single line /// assert_eq!( @@ -266,78 +245,45 @@ macro_rules! __count_elements { #[macro_export] macro_rules! best_fitting { ($least_expanded:expr, $($tail:expr),+ $(,)?) => {{ - let inner = unsafe { - $crate::format_element::BestFitting::from_slice_unchecked(&[$least_expanded, $($tail),+]) - }; - FormatElement::BestFitting(inner) - }} -} - -#[doc(hidden)] -pub struct FormatBuilder { - builder: ConcatBuilder, - result: Result<(), FormatError>, - options: PhantomData, -} - -impl FormatBuilder { - #[inline] - pub fn new(size: usize) -> Self { - let mut builder = ConcatBuilder::new(); - builder.size_hint((size, Some(size))); - - Self { - builder, - result: Ok(()), - options: PhantomData, + unsafe { + $crate::BestFitting::from_arguments_unchecked($crate::format_args!($least_expanded, $($tail),+)) } - } - - #[inline] - pub fn entry(&mut self, element: T, formatter: &Formatter) - where - T: IntoFormatElement, - { - self.result = self.result.and_then(|_| { - self.builder.entry(element.into_format_element(formatter)?); - Ok(()) - }); - } - - #[inline] - pub fn finish(self) -> FormatResult { - self.result.map(|_| self.builder.finish()) - } + }} } #[cfg(test)] mod tests { use crate::prelude::*; + use crate::{write, FormatState, VecBuffer}; struct TestFormat; - impl Format for TestFormat { - type Context = (); - fn format(&self, _: &Formatter) -> FormatResult { - Ok(token("test")) + impl Format<()> for TestFormat { + fn fmt(&self, f: &mut Formatter<()>) -> FormatResult<()> { + write!(f, [token("test")]) } } #[test] fn test_single_element() { - let formatter = Formatter::new(()); + let mut state = FormatState::new(()); + let mut buffer = VecBuffer::new(&mut state); - let formatted = formatted![&formatter, [TestFormat]].unwrap(); + write![&mut buffer, [TestFormat]].unwrap(); - assert_eq!(formatted, token("test")); + assert_eq!( + buffer.into_element(), + FormatElement::Token(Token::Static { text: "test" }) + ); } #[test] fn test_multiple_elements() { - let formatter = Formatter::new(()); + let mut state = FormatState::new(()); + let mut buffer = VecBuffer::new(&mut state); - let formatted = formatted![ - &formatter, + write![ + &mut buffer, [ token("a"), space_token(), @@ -349,14 +295,14 @@ mod tests { .unwrap(); assert_eq!( - formatted, - concat_elements([ - token("a"), - space_token(), - token("simple"), - space_token(), - token("test") - ]) + buffer.into_element(), + FormatElement::List(List::new(vec![ + FormatElement::Token(Token::Static { text: "a" }), + FormatElement::Space, + FormatElement::Token(Token::Static { text: "simple" }), + FormatElement::Space, + FormatElement::Token(Token::Static { text: "test" }) + ])) ); } } diff --git a/crates/rome_formatter/src/prelude.rs b/crates/rome_formatter/src/prelude.rs index 8358c997dfe..9c236dd851b 100644 --- a/crates/rome_formatter/src/prelude.rs +++ b/crates/rome_formatter/src/prelude.rs @@ -1,9 +1,10 @@ +pub use crate::builders::*; pub use crate::format_element::*; -pub use crate::format_extensions::{FormatOptional as _, FormatWith as _, MemoizeFormat}; +pub use crate::format_extensions::{FormatOptional as _, MemoizeFormat}; pub use crate::formatter::Formatter; pub use crate::printer::PrinterOptions; pub use crate::{ - best_fitting, format_elements, formatted, Format, Format as _, FormatError, FormatResult, - FormatRule, FormatWithRule as _, IntoFormatElement as _, + best_fitting, dbg_write, format, format_args, write, Buffer as _, BufferExtensions, Format, + Format as _, FormatError, FormatResult, FormatRule, FormatWithRule as _, SimpleFormatContext, }; diff --git a/crates/rome_formatter/src/printer/mod.rs b/crates/rome_formatter/src/printer/mod.rs index 385820faeea..dbdbb8a8934 100644 --- a/crates/rome_formatter/src/printer/mod.rs +++ b/crates/rome_formatter/src/printer/mod.rs @@ -6,7 +6,7 @@ use crate::format_element::{ ConditionalGroupContent, Group, LineMode, List, PrintMode, VerbatimKind, }; use crate::intersperse::Intersperse; -use crate::{hard_line_break, FormatElement, GroupId, Printed, SourceMarker, TextRange}; +use crate::{FormatElement, GroupId, Printed, SourceMarker, TextRange}; use rome_rowan::TextSize; use std::iter::{once, Rev}; @@ -71,7 +71,6 @@ impl<'a> Printer<'a> { args: PrintElementArgs, ) { match element { - FormatElement::Empty => {} FormatElement::Space => { if self.state.line_width > 0 { self.state.pending_space = true; @@ -167,9 +166,9 @@ impl<'a> Printer<'a> { queue.extend(list.iter().map(|t| PrintElementCall::new(t, args))); } - FormatElement::Indent(indent) => { + FormatElement::Indent(content) => { queue.enqueue(PrintElementCall::new( - &indent.content, + content, args.with_incremented_indent(), )); } @@ -193,11 +192,11 @@ impl<'a> Printer<'a> { } } - FormatElement::Line(line) => { + FormatElement::Line(line_mode) => { if args.mode.is_flat() - && matches!(line.mode, LineMode::Soft | LineMode::SoftOrSpace) + && matches!(line_mode, LineMode::Soft | LineMode::SoftOrSpace) { - if line.mode == LineMode::SoftOrSpace && self.state.line_width > 0 { + if line_mode == &LineMode::SoftOrSpace && self.state.line_width > 0 { self.state.pending_space = true; } } else if !self.state.line_suffixes.is_empty() { @@ -209,7 +208,7 @@ impl<'a> Printer<'a> { } // Print a second line break if this is an empty line - if line.mode == LineMode::Empty && !self.state.has_empty_line { + if line_mode == &LineMode::Empty && !self.state.has_empty_line { self.print_str("\n"); self.state.has_empty_line = true; } @@ -229,7 +228,7 @@ impl<'a> Printer<'a> { .push(PrintElementCall::new(&**suffix, args)); } FormatElement::LineSuffixBoundary => { - const HARD_BREAK: &FormatElement = &hard_line_break(); + const HARD_BREAK: &FormatElement = &FormatElement::Line(LineMode::Hard); self.queue_line_suffixes(HARD_BREAK, args, queue); } @@ -563,7 +562,7 @@ impl Default for PrintElementArgs { } /// The Printer uses a stack that emulates recursion. E.g. recursively processing the elements: -/// `indent(concat(string, string))` would result in the following call stack: +/// `indent(&concat(string, string))` would result in the following call stack: /// /// ```plain /// print_element(indent, indent = 0); @@ -693,17 +692,15 @@ fn fits_element_on_line<'a, 'rest>( options: &PrinterOptions, ) -> Fits { match element { - FormatElement::Empty => {} - FormatElement::Space => { if state.line_width > 0 { state.pending_space = true; } } - FormatElement::Line(line) => { + FormatElement::Line(line_mode) => { if args.mode.is_flat() { - match line.mode { + match line_mode { LineMode::SoftOrSpace => { state.pending_space = true; } @@ -721,8 +718,8 @@ fn fits_element_on_line<'a, 'rest>( } } - FormatElement::Indent(indent) => queue.enqueue(PrintElementCall::new( - &indent.content, + FormatElement::Indent(content) => queue.enqueue(PrintElementCall::new( + content, args.with_incremented_indent(), )), @@ -898,46 +895,56 @@ impl<'a, 'rest> MeasureQueue<'a, 'rest> { mod tests { use crate::prelude::*; use crate::printer::{LineEnding, Printer, PrinterOptions}; - use crate::FormatElement::LineSuffix; - use crate::{LineWidth, Printed}; + use crate::{format_args, write, FormatState, LineWidth, Printed, VecBuffer}; + + fn format(root: &dyn Format<()>) -> Printed { + format_with_options( + root, + PrinterOptions { + indent_string: String::from(" "), + ..PrinterOptions::default() + }, + ) + } - /// Prints the given element with the default printer options - fn print_element>(element: T) -> Printed { - let options = PrinterOptions { - indent_string: String::from(" "), - ..PrinterOptions::default() - }; + fn format_with_options(root: &dyn Format<()>, options: PrinterOptions) -> Printed { + let mut state = FormatState::new(()); + let mut buffer = VecBuffer::new(&mut state); + + write!(&mut buffer, [root]).unwrap(); - Printer::new(options).print(&element.into()) + Printer::new(options).print(&buffer.into_element()) } #[test] fn it_prints_a_group_on_a_single_line_if_it_fits() { - let result = print_element(create_array_element(vec![ - token("\"a\""), - token("\"b\""), - token("\"c\""), - token("\"d\""), - ])); + let result = format(&FormatArrayElements { + items: vec![ + &token("\"a\""), + &token("\"b\""), + &token("\"c\""), + &token("\"d\""), + ], + }); assert_eq!(r#"["a", "b", "c", "d"]"#, result.as_code()) } #[test] fn it_tracks_the_indent_for_each_token() { - let element = format_elements![ + let formatted = format(&format_args!( token("a"), - soft_block_indent(format_elements![ + soft_block_indent(&format_args!( token("b"), - soft_block_indent(format_elements![ + soft_block_indent(&format_args!( token("c"), - soft_block_indent(format_elements![token("d"), soft_line_break(), token("d"),],), + soft_block_indent(&format_args!(token("d"), soft_line_break(), token("d"),)), token("c"), - ],), + )), token("b"), - ],), - token("a"), - ]; + )), + token("a") + )); assert_eq!( r#"a @@ -948,7 +955,7 @@ mod tests { c b a"#, - print_element(element).as_code() + formatted.as_code() ) } @@ -959,14 +966,15 @@ a"#, ..PrinterOptions::default() }; - let program = format_elements![ - token("function main() {"), - block_indent(token("let x = `This is a multiline\nstring`;"),), - token("}"), - hard_line_break(), - ]; - - let result = Printer::new(options).print(&program); + let result = format_with_options( + &format_args![ + token("function main() {"), + block_indent(&token("let x = `This is a multiline\nstring`;")), + token("}"), + hard_line_break() + ], + options, + ); assert_eq!( "function main() {\r\n\tlet x = `This is a multiline\r\nstring`;\r\n}\r\n", @@ -976,10 +984,12 @@ a"#, #[test] fn it_breaks_a_group_if_a_string_contains_a_newline() { - let result = print_element(create_array_element(vec![ - token("`This is a string spanning\ntwo lines`"), - token("\"b\""), - ])); + let result = format(&FormatArrayElements { + items: vec![ + &token("`This is a string spanning\ntwo lines`"), + &token("\"b\""), + ], + }); assert_eq!( r#"[ @@ -990,12 +1000,11 @@ two lines`, result.as_code() ) } - #[test] fn it_breaks_a_group_if_it_contains_a_hard_line_break() { - let result = print_element(group_elements(format_elements![ + let result = format(&group_elements(&format_args![ token("a"), - block_indent(token("b")) + block_indent(&token("b")) ])); assert_eq!("a\n b\n", result.as_code()) @@ -1003,19 +1012,23 @@ two lines`, #[test] fn it_breaks_parent_groups_if_they_dont_fit_on_a_single_line() { - let result = print_element(create_array_element(vec![ - token("\"a\""), - token("\"b\""), - token("\"c\""), - token("\"d\""), - create_array_element(vec![ - token("\"0123456789\""), - token("\"0123456789\""), - token("\"0123456789\""), - token("\"0123456789\""), - token("\"0123456789\""), - ]), - ])); + let result = format(&FormatArrayElements { + items: vec![ + &token("\"a\""), + &token("\"b\""), + &token("\"c\""), + &token("\"d\""), + &FormatArrayElements { + items: vec![ + &token("\"0123456789\""), + &token("\"0123456789\""), + &token("\"0123456789\""), + &token("\"0123456789\""), + &token("\"0123456789\""), + ], + }, + ], + }); assert_eq!( r#"[ @@ -1031,24 +1044,26 @@ two lines`, #[test] fn it_use_the_indent_character_specified_in_the_options() { - let printer = Printer::new(PrinterOptions { + let options = PrinterOptions { indent_string: String::from("\t"), tab_width: 4, print_width: LineWidth::try_from(19).unwrap(), ..PrinterOptions::default() - }); - - let element = - create_array_element(vec![token("'a'"), token("'b'"), token("'c'"), token("'d'")]); + }; - let result = printer.print(&element); + let result = format_with_options( + &FormatArrayElements { + items: vec![&token("'a'"), &token("'b'"), &token("'c'"), &token("'d'")], + }, + options, + ); assert_eq!("[\n\t'a',\n\t\'b',\n\t\'c',\n\t'd',\n]", result.as_code()); } #[test] fn it_prints_consecutive_hard_lines_as_one() { - let result = print_element(format_elements![ + let result = format(&format_args![ token("a"), hard_line_break(), hard_line_break(), @@ -1061,7 +1076,7 @@ two lines`, #[test] fn it_prints_consecutive_empty_lines_as_one() { - let result = print_element(format_elements![ + let result = format(&format_args![ token("a"), empty_line(), empty_line(), @@ -1074,7 +1089,7 @@ two lines`, #[test] fn it_prints_consecutive_mixed_lines_as_one() { - let result = print_element(format_elements![ + let result = format(&format_args![ token("a"), empty_line(), hard_line_break(), @@ -1088,29 +1103,34 @@ two lines`, #[test] fn test_fill_breaks() { - let document = fill_elements( - soft_line_break_or_space(), - vec![ - // These all fit on the same line together - format_elements![token("1"), token(",")], - format_elements![token("2"), token(",")], - format_elements![token("3"), token(",")], - // This one fits on a line by itself, - format_elements![token("723493294"), token(",")], - // fits without breaking - format_elements![group_elements(format_elements![ - token("["), - soft_block_indent(token("5")), - token("],") - ])], - // this one must be printed in expanded mode to fit - group_elements(format_elements![ - token("["), - soft_block_indent(token("123456789")), - token("]"), - ]), - ], - ); + let mut state = FormatState::new(()); + let mut buffer = VecBuffer::new(&mut state); + let mut formatter = Formatter::new(&mut buffer); + + formatter + .fill(&soft_line_break_or_space()) + // These all fit on the same line together + .entry(&format_args!(token("1"), token(","))) + .entry(&format_args!(token("2"), token(","))) + .entry(&format_args!(token("3"), token(","))) + // This one fits on a line by itself, + .entry(&format_args!(token("723493294"), token(","))) + // fits without breaking + .entry(&group_elements(&format_args!( + token("["), + soft_block_indent(&token("5")), + token("],") + ))) + // this one must be printed in expanded mode to fit + .entry(&group_elements(&format_args!( + token("["), + soft_block_indent(&token("123456789")), + token("]"), + ))) + .finish() + .unwrap(); + + let document = buffer.into_element(); let printed = Printer::new(PrinterOptions::default().with_print_width(LineWidth(10))) .print(&document); @@ -1122,43 +1142,50 @@ two lines`, } #[test] - fn line_suffix() { - let document = format_elements![ - group_elements(format_elements![ + fn line_suffix_printed_at_end() { + let printed = format(&format_args![ + group_elements(&format_args![ token("["), - soft_block_indent(format_elements![fill_elements( - soft_line_break_or_space(), - vec![ - format_elements![token("1"), token(",")], - format_elements![token("2"), token(",")], - format_elements![token("3"), if_group_breaks(token(","))] - ] - )]), + soft_block_indent(&format_with(|f| { + f.fill(soft_line_break_or_space()) + .entry(&format_args!(token("1"), token(","))) + .entry(&format_args!(token("2"), token(","))) + .entry(&format_args!(token("3"), if_group_breaks(&token(",")))) + .finish() + })), token("]") ]), token(";"), - comment(LineSuffix(Box::new(format_elements![ + comment(&line_suffix(&format_args![ space_token(), token("// trailing"), space_token() - ]))) - ]; - - let printed = print_element(document); + ])) + ]); assert_eq!(printed.as_code(), "[1, 2, 3]; // trailing") } - fn create_array_element(items: Vec) -> FormatElement { - let separator = format_elements![token(","), soft_line_break_or_space(),]; - - let elements = - format_elements![join_elements(separator, items), if_group_breaks(token(","))]; + struct FormatArrayElements<'a> { + items: Vec<&'a dyn Format<()>>, + } - group_elements(format_elements![ - token("["), - soft_block_indent(elements), - token("]"), - ]) + impl Format<()> for FormatArrayElements<'_> { + fn fmt(&self, f: &mut Formatter<()>) -> FormatResult<()> { + write!( + f, + [group_elements(&format_args!( + token("["), + soft_block_indent(&format_args!( + format_with(|f| f + .join_with(format_args!(token(","), soft_line_break_or_space())) + .entries(&self.items) + .finish()), + if_group_breaks(&token(",")), + )), + token("]") + ))] + ) + } } } diff --git a/crates/rome_js_formatter/README.md b/crates/rome_js_formatter/README.md index 869b4050244..cf6dff8a441 100644 --- a/crates/rome_js_formatter/README.md +++ b/crates/rome_js_formatter/README.md @@ -18,16 +18,17 @@ The foundation of the formatter relies on two pillars: Import the `FormatNode` trait and implement it for your Node. ```rust -use rome_js_formatter::{Format, FormatNode, FormatElement, format_elements, token}; +use rome_js_formatter::prelude::*; +use rome_formatter::{write, format_args}; struct Buzz { blast: String } -impl FormatNode for Buzz { - fn format_fields(&self, formatter: &Formatter) -> FormatResult { +impl Format for Buzz { + fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> { // implementation goes here - format_elements![token("_"), blast.as_str(), token("_")] + write!(f, [token("Hello"), dynamic_token(&self.blast)]) } } @@ -38,11 +39,28 @@ impl FormatNode for Buzz { 1. if a token is mandatory and the AST has that information, please use that token instead, for example: ```rust - fn format_fields(&self, formatter: &Formatter) -> FormatResult { - let l_paren_yes = &self.l_paren_token()?.format(); // yes - let l_paren_no = toke("("); // no + fn fmt_fields(node: Node, f: &mut JsFormatter) -> FormatResult<()> { + write!(f, [node.l_paren_token().format()])?; // yes + write!(f, [token("(")])?; // no } ``` - 1. for tokens that are not mandatory, use our helpers - 1. do not attempt to "fix" the code. If you know a token/node is mandatory, return `None` instead +2. for tokens that are not mandatory, use our helpers +3. do not attempt to "fix" the code. If you know a token/node is mandatory, return `None` instead + +## Debugging formatter output + +You can use the `dbg_write!` macro to output the written IR elements to the console (similar to how the `dbg!` macro works). + +```rust +dbg_write!(f, [ + token("hello"), + space_token(), + token("world") +])?; + +// Writes +// [src/main.rs:1][0] = StaticToken("hello") +// [src/main.rs:1][1] = Space +// [src/main.rs:1][0] = StaticToken("world") +``` diff --git a/crates/rome_js_formatter/docs/implement_the_formatter.md b/crates/rome_js_formatter/docs/implement_the_formatter.md index 4d0f4247686..8c3dfe0b5ea 100644 --- a/crates/rome_js_formatter/docs/implement_the_formatter.md +++ b/crates/rome_js_formatter/docs/implement_the_formatter.md @@ -32,7 +32,7 @@ This will automatically build and open a browser tab to the documentation. 1. Use the `*Fields` struct to extract all the tokens/nodes ```rust impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsExportDefaultExpressionClause, formatter: &Formatter) -> FormatResult { + fn fmt_fields(node: &JsExportDefaultExpressionClause, f: &mut JsFormatter) -> FormatResult<()> { let JsExportDefaultExpressionClauseFields { default_token, expression, @@ -45,7 +45,7 @@ This will automatically build and open a browser tab to the documentation. using the `_` ```rust impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsExportDefaultExpressionClause, formatter: &Formatter) -> FormatResult { + fn fmt_fields(node: &JsExportDefaultExpressionClause, f: &mut JsFormatter) -> FormatResult<()> { let JsExportDefaultExpressionClauseFields { default_token, expression: _, @@ -55,30 +55,32 @@ This will automatically build and open a browser tab to the documentation. } ``` The reason why we want to promote this pattern is because we want to make explicit when a token/node is excluded; -3. Use the APIs provided by `format_element.rs` and `formatter` and `format_extensions.rs`. - 1. `formatter_element.rs` exposes a series of utilities to craft the formatter IR; please refer to their internal +3. Use the APIs provided by `builders.rs`, `formetter` and `format_extensions.rs`. + 1. `builders.rs` exposes a series of utilities to craft the formatter IR; please refer to their internal documentation to understand what the utilities are for; 2. `formatter` exposes a set of functions to help to format some recurring patterns; please refer to their internal documentation to understand how to use them and when; - 3. `format_traits.rs`: with these traits, we give the ability to nodes and tokens to implements certain methods + 3. `format_extensions.rs`: with these traits, we give the ability to nodes and tokens to implements certain methods that are exposed based on its type. If you have a good IDE support, this feature will help you. For example: ```rust impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsExportDefaultExpressionClause, formatter: &Formatter) -> FormatResult { + fn fmt_fields(node: &JsExportDefaultExpressionClause, f: &mut JsFormatter) -> FormatResult<()> { let JsExportDefaultExpressionClauseFields { default_token, expression, // it's a mandatory node semicolon_token, // this is not a mandatory node } = node.as_fields(); let element = expression.format(); - let element = expression.format().with(|element| { - formatted![formatter, element , space_token()] - })?; - let semicolon = semicolon_token.format().format_or(|| space_token())?; - let semicolon = semicolon_token.format(); - let semicolon = semicolon_token.format().with_or_empty(formatter, |semicolon_element| { - formatted![formatter, semicolon_element, space_token()] - })?; + + if let Some(expression) = &expression? { + write!(f, [expression.format(), space_token()])?; + } + + if let Some(semicolon) = &semicolon_token { + write!(f, [semicolon.format()])?; + } else { + write!(f, [space_token()])?; + } } } ``` diff --git a/crates/rome_js_formatter/src/builders.rs b/crates/rome_js_formatter/src/builders.rs new file mode 100644 index 00000000000..7a82cd53797 --- /dev/null +++ b/crates/rome_js_formatter/src/builders.rs @@ -0,0 +1,690 @@ +use crate::prelude::*; +use crate::{AsFormat, TextRange}; +use rome_formatter::{format_args, write, Argument, Arguments, GroupId, PreambleBuffer, VecBuffer}; +use rome_js_syntax::{JsLanguage, JsSyntaxNode, JsSyntaxToken}; +use rome_rowan::syntax::SyntaxTriviaPiecesIterator; +use rome_rowan::{AstNode, Language, SyntaxTriviaPiece}; + +/// Formats a token without its leading or trailing trivia +/// +/// ## Warning +/// It's your responsibility to format leading or trailing comments and skipped trivia. + +pub const fn format_trimmed_token(token: &JsSyntaxToken) -> FormatTrimmedToken { + FormatTrimmedToken { token } +} +#[derive(Debug, Eq, PartialEq, Copy, Clone)] +pub struct FormatTrimmedToken<'a> { + token: &'a JsSyntaxToken, +} + +impl Format for FormatTrimmedToken<'_> { + fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> { + let trimmed_range = self.token.text_trimmed_range(); + + syntax_token_text_slice(self.token, trimmed_range).fmt(f) + } +} + +/// Formats the leading trivia (comments, skipped token trivia) of a token +pub const fn format_leading_trivia( + token: &JsSyntaxToken, + trim_mode: TriviaPrintMode, +) -> FormatLeadingTrivia { + FormatLeadingTrivia { token, trim_mode } +} + +/// Determines if the whitespace separating comment trivias +/// from their associated tokens should be printed or trimmed +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum TriviaPrintMode { + Full, + Trim, +} + +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub struct FormatLeadingTrivia<'a> { + token: &'a JsSyntaxToken, + trim_mode: TriviaPrintMode, +} + +impl Format for FormatLeadingTrivia<'_> { + fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> { + let snapshot = Formatter::snapshot(f); + + match write_leading_trivia_pieces( + self.token.leading_trivia().pieces(), + self.trim_mode, + false, + f, + ) { + Ok(()) => Ok(()), + Err(_) => { + f.restore_snapshot(snapshot); + + write_leading_trivia_with_skipped_tokens(self.token, self.trim_mode, f) + } + } + } +} + +/// Writes the leading trivia pieces of a token. +/// +/// ## Returns +/// +/// Returns [Err] if the leading trivia contains any skipped trivia. Returns the formatted +/// leading trivia otherwise. +fn write_leading_trivia_pieces( + pieces: I, + trim_mode: TriviaPrintMode, + has_trailing_newline: bool, + f: &mut Formatter, +) -> Result<(), FormatError> +where + I: Iterator> + DoubleEndedIterator + ExactSizeIterator, +{ + let mut buffer = VecBuffer::new(f.state_mut()); + + let mut line_count = 0; + + // Get the index of the first comment in the trivia pieces list, and + // checks whether this token has any leading newline the comment + let mut has_leading_newline = false; + let mut first_comment = 0; + + let mut pieces = pieces.enumerate().peekable(); + + // Peek at the next trivia piece, stopping if it is a comment and + // advancing the iterator if it's not + while let Some((index, piece)) = pieces.peek() { + if piece.is_comments() { + // Save the index and break the loop + // without consuming the comment piece + first_comment = *index; + break; + } + + if piece.is_skipped() { + return Err(FormatError::MissingRequiredChild); + } + + if piece.is_newline() { + has_leading_newline = true; + } + + pieces.next(); + } + + // If any newline was found between the previous token and the first comment, + // it will be prepended with a line break instead of a space + let prepend_newline = has_trailing_newline || has_leading_newline; + let mut trim_mode = trim_mode; + + // This consumes the previously created iterator from the last trivia piece + // towards the first (that was not consumed by the previous loop) + for (index, piece) in pieces.rev() { + if let Some(comment_piece) = piece.as_comments() { + let is_single_line = comment_piece.text().starts_with("//"); + + let format_content = format_with(|f| { + if prepend_newline && index == first_comment { + write!(f, [hard_line_break()])?; + } else { + write!(f, [space_token()])?; + }; + + write!(f, [comment(&comment_piece)])?; + + if is_single_line { + match line_count { + 0 | 1 => write!(f, [hard_line_break()])?, + _ => write!(f, [empty_line()])?, + } + } else { + match line_count { + 0 => write!(f, [space_token()])?, + 1 => write!(f, [hard_line_break()])?, + _ => write!(f, [empty_line()])?, + } + }; + + Ok(()) + }); + + write!(buffer, [comment(&format_content)])?; + + line_count = 0; + trim_mode = TriviaPrintMode::Full; + } else if piece.is_newline() && trim_mode == TriviaPrintMode::Full { + line_count += 1; + } else if piece.is_skipped() { + return Err(FormatError::MissingRequiredChild); + } + } + + let elements = buffer.into_vec(); + + for comment in elements.into_iter().rev() { + f.write_element(comment)?; + } + + Ok(()) +} + +/// Writes the leading trivia of a token that has leading skipped trivia. +/// +/// It splits the leading trivia piece into four parts, so that it behaves as if it is a regular token: +/// 1. All pieces that come before the first skipped trivia token. +/// 2. All the skipped trivia pieces, formatted as is. +/// 3. Any trivia after the last skipped token trivia up to, but not including, the first line break. +/// 4. The leading trivia of the token. +/// +/// ## Returns +/// The format element for the tokens leading trivia. +/// +/// ## Panics +/// +/// If called on a token that does not have skipped trivia +fn write_leading_trivia_with_skipped_tokens( + token: &JsSyntaxToken, + trim_mode: TriviaPrintMode, + f: &mut Formatter, +) -> FormatResult<()> { + let mut skipped_trivia_range: Option = None; + // The leading trivia for the first skipped token trivia OR the leading trivia for the token + let mut trailing_trivia = vec![]; + // The trailing trivia for the last skipped token trivia + let mut leading_trivia = vec![]; + // The formatted elements + let mut after_newline = true; + + for piece in token.leading_trivia().pieces() { + if piece.is_skipped() { + if let Some(previous_range) = skipped_trivia_range { + // Another skipped token trivia: `.. first_skipped....piece`. Everything between the skipped token trivia should + // be formatted as is. + skipped_trivia_range = Some(previous_range.cover(piece.text_range())); + // Clear the collected leading/trailing trivia. They are part of the skipped + // token trivia range. + leading_trivia.clear(); + trailing_trivia.clear(); + } else { + // This is the first skipped token trivia. + // Format the collected leading trivia as the leading trivia of this "skipped token trivia" + skipped_trivia_range = Some(piece.text_range()); + + write_leading_trivia_pieces(leading_trivia.drain(..), trim_mode, false, f) + .expect("All skipped trivia pieces should have been filtered out"); + } + + after_newline = false; + continue; + } + + // Everything coming after a new line (including the new line) is considered a leading trivia and not trailing trivia. + if piece.is_newline() { + after_newline = true; + } + + if after_newline { + leading_trivia.push(piece); + } else { + trailing_trivia.push(piece); + } + } + + let skipped_trivia_range = skipped_trivia_range.expect( + "Only call this method for leading trivia containing at least one skipped token trivia.", + ); + + // Format the skipped token trivia range + write!(f, [syntax_token_text_slice(token, skipped_trivia_range)])?; + + // `print_trailing_trivia_pieces` and `format_leading_trivia_pieces` remove any whitespace except + // if there's a comment but removing all whitespace may have a different semantic meaning. + // Insert a: + // * space if the skipped token has no trailing trivia (`skipped\n`, also works for `skipped//comment` because the comment must either be followed by a line break or the token is the EOF). + // * new line if the token has any leading trivia. This can only be the case if there was any new line between the skipped trivia and the token + // * empty: There's literally nothing between skipped and token, so don't insert anything + if !trailing_trivia.is_empty() { + write!(f, [space_token()])?; + } else if !leading_trivia.is_empty() { + write!(f, [hard_line_break()])?; + }; + + // Format the trailing pieces of the skipped token trivia + write!( + f, + [FormatTrailingTriviaPieces { + pieces: trailing_trivia.into_iter() + }] + )?; + + write_leading_trivia_pieces(leading_trivia.into_iter(), trim_mode, after_newline, f) + .expect("All skipped trivia pieces should have been filtered out"); + + Ok(()) +} + +/// Formats the trailing trivia (comments) of a token +pub fn format_trailing_trivia( + token: &JsSyntaxToken, +) -> FormatTrailingTriviaPieces> { + FormatTrailingTriviaPieces { + pieces: token.trailing_trivia().pieces(), + } +} + +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub struct FormatTrailingTriviaPieces { + pieces: I, +} + +impl Format for FormatTrailingTriviaPieces +where + I: Iterator> + Clone, +{ + fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> { + let pieces = self.pieces.clone(); + + for piece in pieces { + if let Some(comment_piece) = piece.as_comments() { + let is_single_line = comment_piece.text().trim_start().starts_with("//"); + + let content = format_with(|f| { + if !is_single_line { + write!(f, [space_token(), comment_piece, space_token()]) + } else { + write![ + f, + [ + line_suffix(&format_args![space_token(), comment_piece]), + expand_parent() + ] + ] + } + }); + + comment(&content).fmt(f)?; + } + } + + Ok(()) + } +} + +/// Formats a node using its [`AsFormat`] implementation but falls back to printing the node as +/// it is in the source document if the formatting returns an [`FormatError`]. +pub const fn format_or_verbatim<'a, Node>(node: &'a Node) -> FormatNodeOrVerbatim<'a, Node> +where + Node: AstNode + AsFormat<'a>, +{ + FormatNodeOrVerbatim { node } +} + +/// Formats a node or falls back to verbatim printing if formating this node fails. +#[derive(Copy, Clone, Eq, PartialEq, Debug)] +pub struct FormatNodeOrVerbatim<'a, Node> { + node: &'a Node, +} + +impl<'a, Node> Format for FormatNodeOrVerbatim<'a, Node> +where + Node: AstNode + AsFormat<'a>, +{ + fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> { + let snapshot = Formatter::snapshot(f); + + match self.node.format().fmt(f) { + Ok(result) => Ok(result), + + Err(_) => { + f.restore_snapshot(snapshot); + + // Lists that yield errors are formatted as they were unknown nodes. + // Doing so, the formatter formats the nodes/tokens as is. + format_unknown_node(self.node.syntax()).fmt(f) + } + } + } +} + +/// Print out a `token` from the original source with a different `content`. +/// +/// This will print the trivia that belong to `token` to `content`; +/// `token` is then marked as consumed by the formatter. +pub fn format_replaced<'a, 'content>( + token: &'a JsSyntaxToken, + content: &'content impl Format, +) -> FormatReplaced<'a, 'content> { + FormatReplaced { + token, + content: Argument::new(content), + } +} + +#[derive(Copy, Clone)] +pub struct FormatReplaced<'a, 'content> { + token: &'a JsSyntaxToken, + content: Argument<'content, JsFormatContext>, +} + +impl Format for FormatReplaced<'_, '_> { + fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> { + f.state_mut().track_token(self.token); + + format_leading_trivia(self.token, TriviaPrintMode::Full).fmt(f)?; + f.write_fmt(Arguments::from(&self.content))?; + format_trailing_trivia(self.token).fmt(f) + } +} + +/// "Formats" a node according to its original formatting in the source text. Being able to format +/// a node "as is" is useful if a node contains syntax errors. Formatting a node with syntax errors +/// has the risk that Rome misinterprets the structure of the code and formatting it could +/// "mess up" the developers, yet incomplete, work or accidentally introduce new syntax errors. +/// +/// You may be inclined to call `node.text` directly. However, using `text` doesn't track the nodes +/// nor its children source mapping information, resulting in incorrect source maps for this subtree. +/// +/// These nodes and tokens get tracked as [FormatElement::Verbatim], useful to understand +/// if these nodes still need to have their own implementation. +pub fn format_verbatim_node(node: &JsSyntaxNode) -> FormatVerbatimNode { + FormatVerbatimNode { + node, + kind: VerbatimKind::Verbatim { + length: node.text_range().len(), + }, + } +} + +#[derive(Debug, Clone, Copy, Eq, PartialEq)] +pub struct FormatVerbatimNode<'node> { + node: &'node JsSyntaxNode, + kind: VerbatimKind, +} +impl Format for FormatVerbatimNode<'_> { + fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> { + for token in self.node.descendants_tokens() { + f.state_mut().track_token(&token); + } + + fn skip_whitespace(piece: &SyntaxTriviaPiece) -> bool { + piece.is_newline() || piece.is_whitespace() + } + + fn write_trivia_token( + f: &mut JsFormatter, + piece: SyntaxTriviaPiece, + ) -> FormatResult<()> { + syntax_token_cow_slice( + normalize_newlines(piece.text(), LINE_TERMINATORS), + &piece.token(), + piece.text_range().start(), + ) + .fmt(f) + } + + let mut buffer = VecBuffer::new(f.state_mut()); + + write!( + buffer, + [format_with(|f| { + for leading_trivia in self + .node + .first_leading_trivia() + .into_iter() + .flat_map(|trivia| trivia.pieces()) + .skip_while(skip_whitespace) + { + write_trivia_token(f, leading_trivia)?; + } + + dynamic_token( + &normalize_newlines(&self.node.text_trimmed().to_string(), LINE_TERMINATORS), + self.node.text_trimmed_range().start(), + ) + .fmt(f)?; + + // Clippy false positive: SkipWhile does not implement DoubleEndedIterator + #[allow(clippy::needless_collect)] + let trailing_trivia: Vec<_> = self + .node + .last_trailing_trivia() + .into_iter() + .flat_map(|trivia| trivia.pieces().rev()) + .skip_while(skip_whitespace) + .collect(); + + for trailing_trivia in trailing_trivia.into_iter().rev() { + write_trivia_token(f, trailing_trivia)?; + } + + Ok(()) + })] + )?; + + let content = buffer.into_element(); + + let verbatim = Verbatim { + element: Box::new(content), + kind: self.kind, + }; + + f.write_element(FormatElement::Verbatim(verbatim)) + } +} + +/// Formats unknown nodes. The difference between this method and `format_verbatim` is that this method +/// doesn't track nodes/tokens as [FormatElement::Verbatim]. They are just printed as they are. +pub fn format_unknown_node(node: &JsSyntaxNode) -> FormatUnknownNode { + FormatUnknownNode { node } +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct FormatUnknownNode<'node> { + node: &'node JsSyntaxNode, +} + +impl Format for FormatUnknownNode<'_> { + fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> { + FormatVerbatimNode { + node: self.node, + kind: VerbatimKind::Unknown, + } + .fmt(f) + } +} + +/// Format a node having formatter suppression comment applied to it +pub fn format_suppressed_node(node: &JsSyntaxNode) -> FormatSuppressedNode { + FormatSuppressedNode { node } +} + +#[derive(Debug, Clone)] +pub struct FormatSuppressedNode<'node> { + node: &'node JsSyntaxNode, +} + +impl Format for FormatSuppressedNode<'_> { + fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> { + // Insert a force a line break to ensure the suppression comment is on its own line + // and correctly registers as a leading trivia on the opening token of this node + write!( + f, + [ + hard_line_break(), + FormatVerbatimNode { + node: self.node, + kind: VerbatimKind::Suppressed + } + ] + ) + } +} + +/// Formats a group delimited by an opening and closing token, +/// such as a function body delimited by '{' and '}' tokens +/// +/// Calling this method is required to correctly handle the comments attached +/// to the opening and closing tokens and insert them inside the group block +pub fn format_delimited<'a, 'content>( + open_token: &'a JsSyntaxToken, + content: &'content impl Format, + close_token: &'a JsSyntaxToken, +) -> FormatDelimited<'a, 'content> { + FormatDelimited { + open_token, + content: Argument::new(content), + close_token, + mode: DelimitedMode::SoftBlockIndent(None), + } +} + +#[derive(Copy, Clone)] +pub struct FormatDelimited<'a, 'content> { + open_token: &'a JsSyntaxToken, + content: Argument<'content, JsFormatContext>, + close_token: &'a JsSyntaxToken, + mode: DelimitedMode, +} + +impl FormatDelimited<'_, '_> { + fn with_mode(mut self, mode: DelimitedMode) -> Self { + self.mode = mode; + self + } + + /// Formats a group delimited by an opening and closing token, placing the + /// content in a [block_indent] group + pub fn block_indent(self) -> Self { + self.with_mode(DelimitedMode::BlockIndent) + } + + /// Formats a group delimited by an opening and closing token, placing the + /// content in a [soft_block_indent] group + pub fn soft_block_indent(self) -> Self { + self.with_mode(DelimitedMode::SoftBlockIndent(None)) + } + + /// Formats a group delimited by an opening and closing token, placing the + /// content in an [indent] group with [soft_line_break_or_space] tokens at the + /// start and end + pub fn soft_block_spaces(self) -> Self { + self.with_mode(DelimitedMode::SoftBlockSpaces(None)) + } + + pub fn soft_block_indent_with_group_id(self, group_id: Option) -> Self { + self.with_mode(DelimitedMode::SoftBlockIndent(group_id)) + } +} + +impl Format for FormatDelimited<'_, '_> { + fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> { + let FormatDelimited { + open_token, + close_token, + content, + mode, + } = self; + + f.state_mut().track_token(open_token); + f.state_mut().track_token(close_token); + + format_leading_trivia(open_token, TriviaPrintMode::Full).fmt(f)?; + + let open_token_trailing_trivia = format_with(|f| { + // Not really interested in the pre-amble, but want to know if it was written + let mut buffer = VecBuffer::new(f.state_mut()); + + write!(buffer, [format_trailing_trivia(open_token)])?; + + let trivia = buffer.into_element(); + + if !trivia.is_empty() { + f.write_element(trivia)?; + soft_line_break_or_space().fmt(f)?; + } + + Ok(()) + }); + + let close_token_leading_trivia = format_with(|f| { + let mut buffer = PreambleBuffer::new(f, soft_line_break_or_space()); + + write!( + buffer, + [format_leading_trivia(close_token, TriviaPrintMode::Trim)] + ) + }); + + let delimited = format_with(|f| { + format_trimmed_token(open_token).fmt(f)?; + + let format_content = format_with(|f| f.write_fmt(Arguments::from(content))); + + match mode { + DelimitedMode::BlockIndent => block_indent(&format_args![ + open_token_trailing_trivia, + format_content, close_token_leading_trivia + ]) + .fmt(f)?, + DelimitedMode::SoftBlockIndent(_) => soft_block_indent(&format_args![ + open_token_trailing_trivia, + format_content, close_token_leading_trivia + ]) + .fmt(f)?, + DelimitedMode::SoftBlockSpaces(_) => { + let mut buffer = VecBuffer::new(f.state_mut()); + write!( + buffer, + [ + open_token_trailing_trivia, + format_content, + close_token_leading_trivia + ] + )?; + let content = buffer.into_element(); + + if !content.is_empty() { + write!( + f, + [ + indent(&format_once(|f| { + write!(f, [soft_line_break_or_space()])?; + f.write_element(content) + }),), + soft_line_break_or_space() + ] + )?; + } + } + }; + + format_trimmed_token(close_token).fmt(f) + }); + + let _grouped = match mode { + // Group is useless, the block indent would expand it right anyway + DelimitedMode::BlockIndent => write!(f, [delimited])?, + DelimitedMode::SoftBlockIndent(group_id) | DelimitedMode::SoftBlockSpaces(group_id) => { + match group_id { + None => write!(f, [group_elements(&delimited)])?, + Some(group_id) => write!( + f, + [group_elements(&delimited).with_group_id(Some(*group_id))] + )?, + } + } + }; + + write!(f, [format_trailing_trivia(close_token)]) + } +} + +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +enum DelimitedMode { + BlockIndent, + SoftBlockIndent(Option), + SoftBlockSpaces(Option), +} diff --git a/crates/rome_js_formatter/src/context.rs b/crates/rome_js_formatter/src/context.rs index ec3bb04d069..e3cc162fa96 100644 --- a/crates/rome_js_formatter/src/context.rs +++ b/crates/rome_js_formatter/src/context.rs @@ -64,7 +64,7 @@ impl FormatContext for JsFormatContext { self.indent_style } - fn line_with(&self) -> LineWidth { + fn line_width(&self) -> LineWidth { self.line_width } diff --git a/crates/rome_js_formatter/src/cst.rs b/crates/rome_js_formatter/src/cst.rs index fe9c8bdf5ca..1c5741933ea 100644 --- a/crates/rome_js_formatter/src/cst.rs +++ b/crates/rome_js_formatter/src/cst.rs @@ -9,8 +9,8 @@ pub struct FormatJsSyntaxNode; impl rome_formatter::FormatRule for FormatJsSyntaxNode { type Context = JsFormatContext; - fn format(node: &JsSyntaxNode, formatter: &JsFormatter) -> FormatResult { - map_syntax_node!(node.clone(), node => formatted![formatter, [node.format()]]) + fn fmt(node: &JsSyntaxNode, f: &mut JsFormatter) -> FormatResult<()> { + map_syntax_node!(node.clone(), node => node.format().fmt(f)) } } @@ -22,7 +22,7 @@ impl<'a> AsFormat<'a> for JsSyntaxNode { } } -impl IntoFormat for JsSyntaxNode { +impl IntoFormat for JsSyntaxNode { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { diff --git a/crates/rome_js_formatter/src/formatter.rs b/crates/rome_js_formatter/src/formatter.rs deleted file mode 100644 index 4855d71b1af..00000000000 --- a/crates/rome_js_formatter/src/formatter.rs +++ /dev/null @@ -1,764 +0,0 @@ -use crate::prelude::*; -use crate::{AsFormat, JsFormatContext}; -use rome_formatter::{normalize_newlines, FormatResult, GroupId, LINE_TERMINATORS}; -use rome_js_syntax::{JsLanguage, JsSyntaxNode, JsSyntaxToken}; -use rome_rowan::{AstNode, AstNodeList, AstSeparatedList, Language, SyntaxTriviaPiece, TextRange}; -use std::iter::once; - -#[derive(Debug, Copy, Clone, Eq, PartialEq)] -pub enum TrailingSeparator { - Allowed, - Disallowed, - Mandatory, -} - -impl TrailingSeparator { - pub fn is_allowed(&self) -> bool { - matches!(self, TrailingSeparator::Allowed) - } - pub fn is_mandatory(&self) -> bool { - matches!(self, TrailingSeparator::Mandatory) - } -} - -impl Default for TrailingSeparator { - fn default() -> Self { - TrailingSeparator::Allowed - } -} - -#[derive(Debug, Default, Copy, Clone)] -pub struct FormatSeparatedOptions { - trailing_separator: TrailingSeparator, - group_id: Option, -} - -impl FormatSeparatedOptions { - pub fn with_trailing_separator(mut self, separator: TrailingSeparator) -> Self { - self.trailing_separator = separator; - self - } - - pub fn with_group_id(mut self, group_id: Option) -> Self { - self.group_id = group_id; - self - } -} - -/// Determines if the whitespace separating comment trivias -/// from their associated tokens should be printed or trimmed -#[derive(Copy, Clone, Debug, Eq, PartialEq)] -pub(super) enum TriviaPrintMode { - Full, - Trim, -} - -/// "Formats" a node according to its original formatting in the source text. Being able to format -/// a node "as is" is useful if a node contains syntax errors. Formatting a node with syntax errors -/// has the risk that Rome misinterprets the structure of the code and formatting it could -/// "mess up" the developers, yet incomplete, work or accidentally introduce new syntax errors. -/// -/// You may be inclined to call `node.text` directly. However, using `text` doesn't track the nodes -/// nor its children source mapping information, resulting in incorrect source maps for this subtree. -/// -/// These nodes and tokens get tracked as [FormatElement::Verbatim], useful to understand -/// if these nodes still need to have their own implementation. -pub fn verbatim_node(node: &JsSyntaxNode) -> FormatVerbatimNode { - FormatVerbatimNode { node } -} - -#[derive(Debug, Clone)] -pub struct FormatVerbatimNode<'node> { - node: &'node JsSyntaxNode, -} - -impl Format for FormatVerbatimNode<'_> { - type Context = JsFormatContext; - - fn format(&self, formatter: &Formatter) -> FormatResult { - let verbatim = format_verbatim_node_or_token(self.node, formatter); - Ok(FormatElement::Verbatim(Verbatim::new_verbatim( - verbatim, - self.node.text_range().len(), - ))) - } -} - -/// Formats unknown nodes. The difference between this method and `format_verbatim` is that this method -/// doesn't track nodes/tokens as [FormatElement::Verbatim]. They are just printed as they are. -pub fn unknown_node(node: &JsSyntaxNode) -> FormatUnknownNode { - FormatUnknownNode { node } -} - -#[derive(Debug, Clone)] -pub struct FormatUnknownNode<'node> { - node: &'node JsSyntaxNode, -} - -impl Format for FormatUnknownNode<'_> { - type Context = JsFormatContext; - - fn format(&self, formatter: &Formatter) -> FormatResult { - Ok(FormatElement::Verbatim(Verbatim::new_unknown( - format_verbatim_node_or_token(self.node, formatter), - ))) - } -} - -/// Format a node having formatter suppression comment applied to it -pub fn suppressed_node(node: &JsSyntaxNode) -> FormatSuppressedNode { - FormatSuppressedNode { node } -} - -#[derive(Debug, Clone)] -pub struct FormatSuppressedNode<'node> { - node: &'node JsSyntaxNode, -} - -impl Format for FormatSuppressedNode<'_> { - type Context = JsFormatContext; - - fn format(&self, formatter: &Formatter) -> FormatResult { - formatted![ - formatter, - [ - // Insert a force a line break to ensure the suppression comment is on its own line - // and correctly registers as a leading trivia on the opening token of this node - hard_line_break(), - FormatElement::Verbatim(Verbatim::new_suppressed(format_verbatim_node_or_token( - self.node, formatter - ))), - ] - ] - } -} - -fn format_verbatim_node_or_token( - node: &JsSyntaxNode, - formatter: &Formatter, -) -> FormatElement { - for token in node.descendants_tokens() { - formatter.track_token(&token); - } - - fn skip_whitespace(piece: &SyntaxTriviaPiece) -> bool { - piece.is_newline() || piece.is_whitespace() - } - - fn trivia_token(piece: SyntaxTriviaPiece) -> Token { - Token::from_syntax_token_cow_slice( - normalize_newlines(piece.text(), LINE_TERMINATORS), - &piece.token(), - piece.text_range().start(), - ) - } - - let leading_trivia = node - .first_leading_trivia() - .into_iter() - .flat_map(|trivia| trivia.pieces()) - .skip_while(skip_whitespace) - .map(trivia_token); - - let content = Token::new_dynamic( - normalize_newlines(&node.text_trimmed().to_string(), LINE_TERMINATORS).into_owned(), - node.text_trimmed_range().start(), - ); - - // Clippy false positive: SkipWhile does not implement DoubleEndedIterator - #[allow(clippy::needless_collect)] - let trailing_trivia = node - .last_trailing_trivia() - .into_iter() - .flat_map(|trivia| trivia.pieces().rev()) - .skip_while(skip_whitespace) - .map(trivia_token) - .collect::>(); - - concat_elements( - leading_trivia - .chain(once(content)) - .chain(trailing_trivia.into_iter().rev()) - .map(FormatElement::from), - ) -} - -pub(crate) fn format_trailing_trivia(token: &JsSyntaxToken) -> FormatElement { - format_trailing_trivia_pieces(token.trailing_trivia().pieces()) -} - -fn format_trailing_trivia_pieces(pieces: I) -> FormatElement -where - I: IntoIterator>, -{ - let mut elements = Vec::new(); - - for piece in pieces { - if let Some(comment) = piece.as_comments() { - let is_single_line = comment.text().trim_start().starts_with("//"); - - let comment = FormatElement::from(Token::from(comment)); - - let content = if !is_single_line { - format_elements![space_token(), comment, space_token(),] - } else { - format_elements![ - line_suffix(format_elements![space_token(), comment]), - expand_parent() - ] - }; - - elements.push(crate::comment(content)); - } - } - - concat_elements(elements) -} - -pub(super) fn format_leading_trivia( - token: &JsSyntaxToken, - trim_mode: TriviaPrintMode, -) -> FormatElement { - format_leading_trivia_pieces(token.leading_trivia().pieces(), trim_mode, false) - .unwrap_or_else(|_| format_leading_trivia_with_skipped_tokens(token, trim_mode)) -} - -/// Formats the leading trivia of a token that has leading skipped trivia. -/// -/// It splits the leading trivia piece into four parts, so that it behaves as if it is a regular token: -/// 1. All pieces that come before the first skipped trivia token. -/// 2. All the skipped trivia pieces, formatted as is. -/// 3. Any trivia after the last skipped token trivia up to, but not including, the first line break. -/// 4. The leading trivia of the token. -/// -/// ## Returns -/// The format element for the tokens leading trivia. -/// -/// ## Panics -/// -/// If called on a token that does not have skipped trivia -fn format_leading_trivia_with_skipped_tokens( - token: &JsSyntaxToken, - trim_mode: TriviaPrintMode, -) -> FormatElement { - let mut skipped_trivia_range: Option = None; - // The leading trivia for the first skipped token trivia OR the leading trivia for the token - let mut trailing_trivia = vec![]; - // The trailing trivia for the last skipped token trivia - let mut leading_trivia = vec![]; - // The formatted elements - let mut elements = vec![]; - let mut after_newline = true; - - for piece in token.leading_trivia().pieces() { - if piece.is_skipped() { - if let Some(previous_range) = skipped_trivia_range { - // Another skipped token trivia: `.. first_skipped....piece`. Everything between the skipped token trivia should - // be formatted as is. - skipped_trivia_range = Some(previous_range.cover(piece.text_range())); - // Clear the collected leading/trailing trivia. They are part of the skipped - // token trivia range. - leading_trivia.clear(); - trailing_trivia.clear(); - } else { - // This is the first skipped token trivia. - // Format the collected leading trivia as the leading trivia of this "skipped token trivia" - skipped_trivia_range = Some(piece.text_range()); - elements.push( - format_leading_trivia_pieces(leading_trivia.drain(..), trim_mode, false) - .expect("All skipped trivia pieces should have been filtered out"), - ); - } - - after_newline = false; - continue; - } - - // Everything coming after a new line (including the new line) is considered a leading trivia and not trailing trivia. - if piece.is_newline() { - after_newline = true; - } - - if after_newline { - leading_trivia.push(piece); - } else { - trailing_trivia.push(piece); - } - } - - let skipped_trivia_range = skipped_trivia_range.expect( - "Only call this method for leading trivia containing at least one skipped token trivia.", - ); - - // Format the skipped token trivia range - elements.push(FormatElement::from(Token::new_syntax_token_slice( - token, - skipped_trivia_range, - ))); - - // `print_trailing_trivia_pieces` and `format_leading_trivia_pieces` remove any whitespace except - // if there's a comment but removing all whitespace may have a different semantic meaning. - // Insert a: - // * space if the skipped token has no trailing trivia (`skipped\n`, also works for `skipped//comment` because the comment must either be followed by a line break or the token is the EOF). - // * new line if the token has any leading trivia. This can only be the case if there was any new line between the skipped trivia and the token - // * empty: There's literally nothing between skipped and token, so don't insert anything - let skipped_separator = if !trailing_trivia.is_empty() { - space_token() - } else if !leading_trivia.is_empty() { - hard_line_break() - } else { - empty_element() - }; - - elements.push(skipped_separator); - // Format the trailing pieces of the skipped token trivia - elements.push(format_trailing_trivia_pieces(trailing_trivia)); - - elements.push( - format_leading_trivia_pieces(leading_trivia.into_iter(), trim_mode, after_newline) - .expect("All skipped trivia pieces should have been filtered out"), - ); - - concat_elements(elements) -} - -/// Formats the leading trivia pieces of a token. -/// -/// ## Returns -/// -/// Returns [Err] if the leading trivia contains any skipped trivia. Returns the formatted -/// leading trivia otherwise. -fn format_leading_trivia_pieces( - pieces: I, - mut trim_mode: TriviaPrintMode, - has_trailing_newline: bool, -) -> Result -where - I: Iterator> + DoubleEndedIterator + ExactSizeIterator, -{ - let mut line_count = 0; - let mut elements = Vec::new(); - - // Get the index of the first comment in the trivia pieces list, and - // checks whether this token has any leading newline the comment - let mut has_leading_newline = false; - let mut first_comment = 0; - - let mut pieces = pieces.enumerate().peekable(); - - // Peek at the next trivia piece, stopping if it is a comment and - // advancing the iterator if it's not - while let Some((index, piece)) = pieces.peek() { - if piece.is_comments() { - // Save the index and break the loop - // without consuming the comment piece - first_comment = *index; - break; - } - - if piece.is_skipped() { - return Err(()); - } - - if piece.is_newline() { - has_leading_newline = true; - } - - pieces.next(); - } - - // If any newline was found between the previous token and the first comment, - // it will be prepended with a line break instead of a space - let prepend_newline = has_trailing_newline || has_leading_newline; - - // This consumes the previously created iterator from the last trivia piece - // towards the first (that was not consumed by the previous loop) - for (index, piece) in pieces.rev() { - if let Some(comment) = piece.as_comments() { - let is_single_line = comment.text().starts_with("//"); - - let comment = FormatElement::from(Token::from(comment)); - - let element_before_comment = if prepend_newline && index == first_comment { - hard_line_break() - } else { - space_token() - }; - - let element_after_comment = if is_single_line { - match line_count { - 0 | 1 => hard_line_break(), - _ => empty_line(), - } - } else { - match line_count { - 0 => space_token(), - 1 => hard_line_break(), - _ => empty_line(), - } - }; - - elements.push(crate::comment(format_elements![ - element_before_comment, - comment, - element_after_comment, - ])); - - line_count = 0; - trim_mode = TriviaPrintMode::Full; - } else if piece.is_newline() && trim_mode == TriviaPrintMode::Full { - line_count += 1; - } else if piece.is_skipped() { - return Err(()); - } - } - - Ok(concat_elements(elements.into_iter().rev())) -} - -pub(crate) type JsFormatter = Formatter; - -/// JS specific formatter extensions -pub(crate) trait JsFormatterExt { - fn as_formatter(&self) -> &Formatter; - - #[must_use] - fn delimited<'a, 'fmt>( - &'fmt self, - open_token: &'a JsSyntaxToken, - content: FormatElement, - close_token: &'a JsSyntaxToken, - ) -> FormatDelimited<'a, 'fmt> { - FormatDelimited::new(open_token, content, close_token, self.as_formatter()) - } - - /// Print out a `token` from the original source with a different `content`. - /// - /// This will print the trivias that belong to `token` to `content`; - /// `token` is then marked as consumed by the formatter. - fn format_replaced( - &self, - current_token: &JsSyntaxToken, - content_to_replace_with: FormatElement, - ) -> FormatElement { - let formatter = self.as_formatter(); - - formatter.track_token(current_token); - - format_elements![ - format_leading_trivia(current_token, TriviaPrintMode::Full), - content_to_replace_with, - format_trailing_trivia(current_token), - ] - } - - /// Prints a separated list of nodes - /// - /// Trailing separators will be reused from the original list or - /// created by calling the `separator_factory` function. - /// The last trailing separator in the list will only be printed - /// if the outer group breaks. - fn format_separated( - &self, - list: &L, - separator_factory: F, - ) -> FormatResult> - where - L: AstSeparatedList, - for<'a> L::Node: AstNode + AsFormat<'a>, - F: Fn() -> FormatElement, - { - self.format_separated_with_options( - list, - separator_factory, - FormatSeparatedOptions::default(), - ) - } - - /// Prints a separated list of nodes - /// - /// Trailing separators will be reused from the original list or - /// created by calling the `separator_factory` function. - /// The last trailing separator in the list will only be printed - /// if the outer group breaks. - fn format_separated_with_options( - &self, - list: &L, - separator_factory: F, - options: FormatSeparatedOptions, - ) -> FormatResult> - where - L: AstSeparatedList, - for<'a> L::Node: AstNode + AsFormat<'a>, - F: Fn() -> FormatElement, - { - let mut result = Vec::with_capacity(list.len()); - let last_index = list.len().saturating_sub(1); - let formatter = self.as_formatter(); - - let trailing_separator_factory = || { - if let Some(group_id) = options.group_id { - if_group_with_id_breaks(separator_factory(), group_id) - } else { - if_group_breaks(separator_factory()) - } - }; - - let trailing_separator = options.trailing_separator; - - for (index, element) in list.elements().enumerate() { - let node = formatted![formatter, [element.node()?.format()]]?; - - // Reuse the existing trailing separator or create it if it wasn't in the - // input source. Only print the last trailing token if the outer group breaks - let separator = if let Some(separator) = element.trailing_separator()? { - if index == last_index { - if trailing_separator.is_allowed() { - // Use format_replaced instead of wrapping the result of format_token - // in order to remove only the token itself when the group doesn't break - // but still print its associated trivias unconditionally - self.format_replaced(separator, trailing_separator_factory()) - } else if trailing_separator.is_mandatory() { - formatted![formatter, [separator.format()]]? - } else { - empty_element() - } - } else { - formatted![formatter, [separator.format()]]? - } - } else if index == last_index { - if trailing_separator.is_allowed() { - trailing_separator_factory() - } else if trailing_separator.is_mandatory() { - separator_factory() - } else { - empty_element() - } - } else { - separator_factory() - }; - - result.push(format_elements![group_elements(node), separator]); - } - - Ok(result.into_iter()) - } - - /// It formats a list of nodes that are not separated. It's an ad-hoc function to - /// format lists that implement [rome_js_syntax::AstNodeList]. - /// - /// The elements of the list are joined together using [join_elements_hard_line], which will - /// end up separated by hard lines or empty lines. - /// - /// If the formatter fails to format an element, said element gets printed verbatim. - fn format_list(&self, list: &List) -> FormatElement - where - List: AstNodeList, - for<'a> Node: AstNode + AsFormat<'a>, - { - let formatter = self.as_formatter(); - let formatted_list = list.iter().map(|module_item| { - let snapshot = formatter.snapshot(); - let format = module_item.format(); - - let elem = match formatted![formatter, [format]] { - Ok(result) => result, - Err(_) => { - formatter.restore(snapshot); - - // Lists that yield errors are formatted as they were unknown nodes. - // Doing so, the formatter formats the nodes/tokens as is. - // SAFETY: `FormatUnknownNode` always returns Ok - unknown_node(module_item.syntax()) - .format(formatter) - .unwrap() - } - }; - - (module_item.syntax().clone(), elem) - }); - join_elements_hard_line(formatted_list) - } -} - -impl JsFormatterExt for Formatter { - fn as_formatter(&self) -> &Formatter { - self - } -} - -/// Formats a group delimited by an opening and closing token, -/// such as a function body delimited by '{' and '}' tokens -/// -/// Calling this method is required to correctly handle the comments attached -/// to the opening and closing tokens and insert them inside the group block -pub struct FormatDelimited<'a, 'fmt> { - open_token: &'a JsSyntaxToken, - content: FormatElement, - close_token: &'a JsSyntaxToken, - mode: DelimitedMode, - formatter: &'fmt Formatter, -} - -impl<'a, 'fmt> FormatDelimited<'a, 'fmt> { - fn new( - open_token: &'a JsSyntaxToken, - content: FormatElement, - close_token: &'a JsSyntaxToken, - formatter: &'fmt Formatter, - ) -> Self { - Self { - open_token, - content, - close_token, - mode: DelimitedMode::SoftBlockIndent(None), - formatter, - } - } - - fn with_mode(mut self, mode: DelimitedMode) -> Self { - self.mode = mode; - self - } - - /// Formats a group delimited by an opening and closing token, placing the - /// content in a [block_indent] group - pub fn block_indent(self) -> Self { - self.with_mode(DelimitedMode::BlockIndent) - } - - /// Formats a group delimited by an opening and closing token, placing the - /// content in a [soft_block_indent] group - pub fn soft_block_indent(self) -> Self { - self.with_mode(DelimitedMode::SoftBlockIndent(None)) - } - - /// Formats a group delimited by an opening and closing token, placing the - /// content in an [indent] group with [soft_line_break_or_space] tokens at the - /// start and end - pub fn soft_block_spaces(self) -> Self { - self.with_mode(DelimitedMode::SoftBlockSpaces(None)) - } - - pub fn soft_block_indent_with_group_id(self, group_id: Option) -> Self { - self.with_mode(DelimitedMode::SoftBlockIndent(group_id)) - } - - pub fn soft_block_spaces_with_group_id(self, group_id: Option) -> Self { - self.with_mode(DelimitedMode::SoftBlockSpaces(group_id)) - } - - pub fn finish(self) -> FormatResult { - let FormatDelimited { - formatter, - open_token, - close_token, - content, - mode, - } = self; - - formatter.track_token(open_token); - formatter.track_token(close_token); - - let open_token_trailing_trivia = format_trailing_trivia(open_token); - let close_token_leading_trivia = format_leading_trivia(close_token, TriviaPrintMode::Trim); - - let open_token_trailing_trivia = if !open_token_trailing_trivia.is_empty() { - formatted![ - formatter, - [open_token_trailing_trivia, soft_line_break_or_space()] - ]? - } else { - empty_element() - }; - let close_token_leading_trivia = if !close_token_leading_trivia.is_empty() { - formatted![ - formatter, - [soft_line_break_or_space(), close_token_leading_trivia] - ]? - } else { - empty_element() - }; - - let formatted_content = match mode { - DelimitedMode::BlockIndent => block_indent(formatted![ - formatter, - [ - open_token_trailing_trivia, - content, - close_token_leading_trivia - ] - ]?), - DelimitedMode::SoftBlockIndent(_) => soft_block_indent(formatted![ - formatter, - [ - open_token_trailing_trivia, - content, - close_token_leading_trivia - ] - ]?), - DelimitedMode::SoftBlockSpaces(_) => { - if open_token_trailing_trivia.is_empty() - && content.is_empty() - && close_token_leading_trivia.is_empty() - { - empty_element() - } else { - formatted![ - formatter, - [ - indent(formatted![ - formatter, - [ - soft_line_break_or_space(), - open_token_trailing_trivia, - content, - close_token_leading_trivia, - ] - ]?), - soft_line_break_or_space(), - ] - ]? - } - } - }; - - let delimited = format_elements![ - Token::from(open_token), - formatted_content, - Token::from(close_token), - ]; - - let grouped = match mode { - // Group is useless, the block indent would expand it right anyway - DelimitedMode::BlockIndent => delimited, - DelimitedMode::SoftBlockIndent(group_id) | DelimitedMode::SoftBlockSpaces(group_id) => { - match group_id { - None => group_elements(delimited), - Some(group_id) => group_elements_with_options( - delimited, - GroupElementsOptions { - group_id: Some(group_id), - }, - ), - } - } - }; - - formatted![ - formatter, - [ - format_leading_trivia(open_token, TriviaPrintMode::Full), - grouped, - format_trailing_trivia(close_token), - ] - ] - } -} - -#[derive(Debug, Copy, Clone, Eq, PartialEq)] -enum DelimitedMode { - BlockIndent, - SoftBlockIndent(Option), - SoftBlockSpaces(Option), -} diff --git a/crates/rome_js_formatter/src/generated.rs b/crates/rome_js_formatter/src/generated.rs index ebba0090034..e0a46d0e076 100644 --- a/crates/rome_js_formatter/src/generated.rs +++ b/crates/rome_js_formatter/src/generated.rs @@ -7,7 +7,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsScript { FormatRefWithRule<'a, rome_js_syntax::JsScript, FormatNodeRule>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsScript { +impl IntoFormat for rome_js_syntax::JsScript { type Format = FormatOwnedWithRule>; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -17,7 +17,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsModule { FormatRefWithRule<'a, rome_js_syntax::JsModule, FormatNodeRule>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsModule { +impl IntoFormat for rome_js_syntax::JsModule { type Format = FormatOwnedWithRule>; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -30,7 +30,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsExpressionSnipped { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsExpressionSnipped { +impl IntoFormat for rome_js_syntax::JsExpressionSnipped { type Format = FormatOwnedWithRule< rome_js_syntax::JsExpressionSnipped, FormatNodeRule, @@ -45,7 +45,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsDirective { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsDirective { +impl IntoFormat for rome_js_syntax::JsDirective { type Format = FormatOwnedWithRule< rome_js_syntax::JsDirective, FormatNodeRule, @@ -60,7 +60,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsBlockStatement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsBlockStatement { +impl IntoFormat for rome_js_syntax::JsBlockStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsBlockStatement, FormatNodeRule, @@ -75,7 +75,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsBreakStatement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsBreakStatement { +impl IntoFormat for rome_js_syntax::JsBreakStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsBreakStatement, FormatNodeRule, @@ -90,7 +90,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsClassDeclaration { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsClassDeclaration { +impl IntoFormat for rome_js_syntax::JsClassDeclaration { type Format = FormatOwnedWithRule< rome_js_syntax::JsClassDeclaration, FormatNodeRule, @@ -105,7 +105,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsContinueStatement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsContinueStatement { +impl IntoFormat for rome_js_syntax::JsContinueStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsContinueStatement, FormatNodeRule, @@ -120,7 +120,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsDebuggerStatement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsDebuggerStatement { +impl IntoFormat for rome_js_syntax::JsDebuggerStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsDebuggerStatement, FormatNodeRule, @@ -135,7 +135,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsDoWhileStatement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsDoWhileStatement { +impl IntoFormat for rome_js_syntax::JsDoWhileStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsDoWhileStatement, FormatNodeRule, @@ -150,7 +150,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsEmptyStatement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsEmptyStatement { +impl IntoFormat for rome_js_syntax::JsEmptyStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsEmptyStatement, FormatNodeRule, @@ -165,7 +165,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsExpressionStatement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsExpressionStatement { +impl IntoFormat for rome_js_syntax::JsExpressionStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsExpressionStatement, FormatNodeRule, @@ -180,7 +180,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsForInStatement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsForInStatement { +impl IntoFormat for rome_js_syntax::JsForInStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsForInStatement, FormatNodeRule, @@ -195,7 +195,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsForOfStatement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsForOfStatement { +impl IntoFormat for rome_js_syntax::JsForOfStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsForOfStatement, FormatNodeRule, @@ -210,7 +210,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsForStatement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsForStatement { +impl IntoFormat for rome_js_syntax::JsForStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsForStatement, FormatNodeRule, @@ -225,7 +225,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsIfStatement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsIfStatement { +impl IntoFormat for rome_js_syntax::JsIfStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsIfStatement, FormatNodeRule, @@ -240,7 +240,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsLabeledStatement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsLabeledStatement { +impl IntoFormat for rome_js_syntax::JsLabeledStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsLabeledStatement, FormatNodeRule, @@ -255,7 +255,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsReturnStatement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsReturnStatement { +impl IntoFormat for rome_js_syntax::JsReturnStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsReturnStatement, FormatNodeRule, @@ -270,7 +270,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsSwitchStatement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsSwitchStatement { +impl IntoFormat for rome_js_syntax::JsSwitchStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsSwitchStatement, FormatNodeRule, @@ -285,7 +285,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsThrowStatement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsThrowStatement { +impl IntoFormat for rome_js_syntax::JsThrowStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsThrowStatement, FormatNodeRule, @@ -300,7 +300,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsTryFinallyStatement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsTryFinallyStatement { +impl IntoFormat for rome_js_syntax::JsTryFinallyStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsTryFinallyStatement, FormatNodeRule, @@ -315,7 +315,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsTryStatement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsTryStatement { +impl IntoFormat for rome_js_syntax::JsTryStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsTryStatement, FormatNodeRule, @@ -330,7 +330,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsVariableStatement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsVariableStatement { +impl IntoFormat for rome_js_syntax::JsVariableStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsVariableStatement, FormatNodeRule, @@ -345,7 +345,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsWhileStatement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsWhileStatement { +impl IntoFormat for rome_js_syntax::JsWhileStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsWhileStatement, FormatNodeRule, @@ -360,7 +360,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsWithStatement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsWithStatement { +impl IntoFormat for rome_js_syntax::JsWithStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsWithStatement, FormatNodeRule, @@ -375,7 +375,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsFunctionDeclaration { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsFunctionDeclaration { +impl IntoFormat for rome_js_syntax::JsFunctionDeclaration { type Format = FormatOwnedWithRule< rome_js_syntax::JsFunctionDeclaration, FormatNodeRule, @@ -390,7 +390,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsEnumDeclaration { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsEnumDeclaration { +impl IntoFormat for rome_js_syntax::TsEnumDeclaration { type Format = FormatOwnedWithRule< rome_js_syntax::TsEnumDeclaration, FormatNodeRule, @@ -405,7 +405,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeAliasDeclaration { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsTypeAliasDeclaration { +impl IntoFormat for rome_js_syntax::TsTypeAliasDeclaration { type Format = FormatOwnedWithRule< rome_js_syntax::TsTypeAliasDeclaration, FormatNodeRule, @@ -420,7 +420,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsInterfaceDeclaration { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsInterfaceDeclaration { +impl IntoFormat for rome_js_syntax::TsInterfaceDeclaration { type Format = FormatOwnedWithRule< rome_js_syntax::TsInterfaceDeclaration, FormatNodeRule, @@ -435,7 +435,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsDeclareFunctionDeclaration { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsDeclareFunctionDeclaration { +impl IntoFormat for rome_js_syntax::TsDeclareFunctionDeclaration { type Format = FormatOwnedWithRule< rome_js_syntax::TsDeclareFunctionDeclaration, FormatNodeRule, @@ -450,7 +450,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsDeclareStatement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsDeclareStatement { +impl IntoFormat for rome_js_syntax::TsDeclareStatement { type Format = FormatOwnedWithRule< rome_js_syntax::TsDeclareStatement, FormatNodeRule, @@ -465,7 +465,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsModuleDeclaration { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsModuleDeclaration { +impl IntoFormat for rome_js_syntax::TsModuleDeclaration { type Format = FormatOwnedWithRule< rome_js_syntax::TsModuleDeclaration, FormatNodeRule, @@ -480,7 +480,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsExternalModuleDeclaration { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsExternalModuleDeclaration { +impl IntoFormat for rome_js_syntax::TsExternalModuleDeclaration { type Format = FormatOwnedWithRule< rome_js_syntax::TsExternalModuleDeclaration, FormatNodeRule, @@ -495,7 +495,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsGlobalDeclaration { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsGlobalDeclaration { +impl IntoFormat for rome_js_syntax::TsGlobalDeclaration { type Format = FormatOwnedWithRule< rome_js_syntax::TsGlobalDeclaration, FormatNodeRule, @@ -510,7 +510,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsImportEqualsDeclaration { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsImportEqualsDeclaration { +impl IntoFormat for rome_js_syntax::TsImportEqualsDeclaration { type Format = FormatOwnedWithRule< rome_js_syntax::TsImportEqualsDeclaration, FormatNodeRule, @@ -525,7 +525,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsElseClause { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsElseClause { +impl IntoFormat for rome_js_syntax::JsElseClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsElseClause, FormatNodeRule, @@ -540,7 +540,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsVariableDeclaration { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsVariableDeclaration { +impl IntoFormat for rome_js_syntax::JsVariableDeclaration { type Format = FormatOwnedWithRule< rome_js_syntax::JsVariableDeclaration, FormatNodeRule, @@ -555,7 +555,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsForVariableDeclaration { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsForVariableDeclaration { +impl IntoFormat for rome_js_syntax::JsForVariableDeclaration { type Format = FormatOwnedWithRule< rome_js_syntax::JsForVariableDeclaration, FormatNodeRule, @@ -570,7 +570,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsVariableDeclarator { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsVariableDeclarator { +impl IntoFormat for rome_js_syntax::JsVariableDeclarator { type Format = FormatOwnedWithRule< rome_js_syntax::JsVariableDeclarator, FormatNodeRule, @@ -585,7 +585,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsCaseClause { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsCaseClause { +impl IntoFormat for rome_js_syntax::JsCaseClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsCaseClause, FormatNodeRule, @@ -600,7 +600,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsDefaultClause { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsDefaultClause { +impl IntoFormat for rome_js_syntax::JsDefaultClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsDefaultClause, FormatNodeRule, @@ -615,7 +615,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsCatchClause { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsCatchClause { +impl IntoFormat for rome_js_syntax::JsCatchClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsCatchClause, FormatNodeRule, @@ -630,7 +630,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsFinallyClause { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsFinallyClause { +impl IntoFormat for rome_js_syntax::JsFinallyClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsFinallyClause, FormatNodeRule, @@ -645,7 +645,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsCatchDeclaration { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsCatchDeclaration { +impl IntoFormat for rome_js_syntax::JsCatchDeclaration { type Format = FormatOwnedWithRule< rome_js_syntax::JsCatchDeclaration, FormatNodeRule, @@ -660,7 +660,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeAnnotation { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsTypeAnnotation { +impl IntoFormat for rome_js_syntax::TsTypeAnnotation { type Format = FormatOwnedWithRule< rome_js_syntax::TsTypeAnnotation, FormatNodeRule, @@ -675,7 +675,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::ImportMeta { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::ImportMeta { +impl IntoFormat for rome_js_syntax::ImportMeta { type Format = FormatOwnedWithRule>; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -688,7 +688,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsArrayExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsArrayExpression { +impl IntoFormat for rome_js_syntax::JsArrayExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsArrayExpression, FormatNodeRule, @@ -703,7 +703,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsArrowFunctionExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsArrowFunctionExpression { +impl IntoFormat for rome_js_syntax::JsArrowFunctionExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsArrowFunctionExpression, FormatNodeRule, @@ -718,7 +718,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAssignmentExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAssignmentExpression { +impl IntoFormat for rome_js_syntax::JsAssignmentExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsAssignmentExpression, FormatNodeRule, @@ -733,7 +733,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAwaitExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAwaitExpression { +impl IntoFormat for rome_js_syntax::JsAwaitExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsAwaitExpression, FormatNodeRule, @@ -748,7 +748,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsBinaryExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsBinaryExpression { +impl IntoFormat for rome_js_syntax::JsBinaryExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsBinaryExpression, FormatNodeRule, @@ -763,7 +763,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsCallExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsCallExpression { +impl IntoFormat for rome_js_syntax::JsCallExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsCallExpression, FormatNodeRule, @@ -778,7 +778,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsClassExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsClassExpression { +impl IntoFormat for rome_js_syntax::JsClassExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsClassExpression, FormatNodeRule, @@ -793,7 +793,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsComputedMemberExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsComputedMemberExpression { +impl IntoFormat for rome_js_syntax::JsComputedMemberExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsComputedMemberExpression, FormatNodeRule, @@ -808,7 +808,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsConditionalExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsConditionalExpression { +impl IntoFormat for rome_js_syntax::JsConditionalExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsConditionalExpression, FormatNodeRule, @@ -823,7 +823,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsFunctionExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsFunctionExpression { +impl IntoFormat for rome_js_syntax::JsFunctionExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsFunctionExpression, FormatNodeRule, @@ -838,7 +838,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsIdentifierExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsIdentifierExpression { +impl IntoFormat for rome_js_syntax::JsIdentifierExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsIdentifierExpression, FormatNodeRule, @@ -853,7 +853,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsImportCallExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsImportCallExpression { +impl IntoFormat for rome_js_syntax::JsImportCallExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsImportCallExpression, FormatNodeRule, @@ -868,7 +868,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsInExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsInExpression { +impl IntoFormat for rome_js_syntax::JsInExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsInExpression, FormatNodeRule, @@ -883,7 +883,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsInstanceofExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsInstanceofExpression { +impl IntoFormat for rome_js_syntax::JsInstanceofExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsInstanceofExpression, FormatNodeRule, @@ -898,7 +898,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsLogicalExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsLogicalExpression { +impl IntoFormat for rome_js_syntax::JsLogicalExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsLogicalExpression, FormatNodeRule, @@ -913,7 +913,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsNewExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsNewExpression { +impl IntoFormat for rome_js_syntax::JsNewExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsNewExpression, FormatNodeRule, @@ -928,7 +928,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsObjectExpression { +impl IntoFormat for rome_js_syntax::JsObjectExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsObjectExpression, FormatNodeRule, @@ -943,7 +943,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsParenthesizedExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsParenthesizedExpression { +impl IntoFormat for rome_js_syntax::JsParenthesizedExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsParenthesizedExpression, FormatNodeRule, @@ -958,7 +958,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsPostUpdateExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsPostUpdateExpression { +impl IntoFormat for rome_js_syntax::JsPostUpdateExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsPostUpdateExpression, FormatNodeRule, @@ -973,7 +973,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsPreUpdateExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsPreUpdateExpression { +impl IntoFormat for rome_js_syntax::JsPreUpdateExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsPreUpdateExpression, FormatNodeRule, @@ -988,7 +988,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsSequenceExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsSequenceExpression { +impl IntoFormat for rome_js_syntax::JsSequenceExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsSequenceExpression, FormatNodeRule, @@ -1003,7 +1003,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsStaticMemberExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsStaticMemberExpression { +impl IntoFormat for rome_js_syntax::JsStaticMemberExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsStaticMemberExpression, FormatNodeRule, @@ -1018,7 +1018,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsSuperExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsSuperExpression { +impl IntoFormat for rome_js_syntax::JsSuperExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsSuperExpression, FormatNodeRule, @@ -1033,7 +1033,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsThisExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsThisExpression { +impl IntoFormat for rome_js_syntax::JsThisExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsThisExpression, FormatNodeRule, @@ -1048,7 +1048,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsUnaryExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsUnaryExpression { +impl IntoFormat for rome_js_syntax::JsUnaryExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsUnaryExpression, FormatNodeRule, @@ -1063,7 +1063,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsYieldExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsYieldExpression { +impl IntoFormat for rome_js_syntax::JsYieldExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsYieldExpression, FormatNodeRule, @@ -1075,7 +1075,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::NewTarget { FormatRefWithRule<'a, rome_js_syntax::NewTarget, FormatNodeRule>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::NewTarget { +impl IntoFormat for rome_js_syntax::NewTarget { type Format = FormatOwnedWithRule>; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -1088,7 +1088,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsTemplate { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsTemplate { +impl IntoFormat for rome_js_syntax::JsTemplate { type Format = FormatOwnedWithRule>; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -1101,7 +1101,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeAssertionExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsTypeAssertionExpression { +impl IntoFormat for rome_js_syntax::TsTypeAssertionExpression { type Format = FormatOwnedWithRule< rome_js_syntax::TsTypeAssertionExpression, FormatNodeRule, @@ -1116,7 +1116,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAsExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsAsExpression { +impl IntoFormat for rome_js_syntax::TsAsExpression { type Format = FormatOwnedWithRule< rome_js_syntax::TsAsExpression, FormatNodeRule, @@ -1131,7 +1131,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsNonNullAssertionExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsNonNullAssertionExpression { +impl IntoFormat for rome_js_syntax::TsNonNullAssertionExpression { type Format = FormatOwnedWithRule< rome_js_syntax::TsNonNullAssertionExpression, FormatNodeRule, @@ -1146,7 +1146,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxTagExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsxTagExpression { +impl IntoFormat for rome_js_syntax::JsxTagExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsxTagExpression, FormatNodeRule, @@ -1161,7 +1161,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeArguments { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsTypeArguments { +impl IntoFormat for rome_js_syntax::TsTypeArguments { type Format = FormatOwnedWithRule< rome_js_syntax::TsTypeArguments, FormatNodeRule, @@ -1176,7 +1176,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsTemplateChunkElement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsTemplateChunkElement { +impl IntoFormat for rome_js_syntax::JsTemplateChunkElement { type Format = FormatOwnedWithRule< rome_js_syntax::JsTemplateChunkElement, FormatNodeRule, @@ -1191,7 +1191,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsTemplateElement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsTemplateElement { +impl IntoFormat for rome_js_syntax::JsTemplateElement { type Format = FormatOwnedWithRule< rome_js_syntax::JsTemplateElement, FormatNodeRule, @@ -1206,7 +1206,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsCallArguments { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsCallArguments { +impl IntoFormat for rome_js_syntax::JsCallArguments { type Format = FormatOwnedWithRule< rome_js_syntax::JsCallArguments, FormatNodeRule, @@ -1221,7 +1221,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsYieldArgument { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsYieldArgument { +impl IntoFormat for rome_js_syntax::JsYieldArgument { type Format = FormatOwnedWithRule< rome_js_syntax::JsYieldArgument, FormatNodeRule, @@ -1236,7 +1236,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeParameters { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsTypeParameters { +impl IntoFormat for rome_js_syntax::TsTypeParameters { type Format = FormatOwnedWithRule< rome_js_syntax::TsTypeParameters, FormatNodeRule, @@ -1251,7 +1251,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsParameters { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsParameters { +impl IntoFormat for rome_js_syntax::JsParameters { type Format = FormatOwnedWithRule< rome_js_syntax::JsParameters, FormatNodeRule, @@ -1266,7 +1266,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsReturnTypeAnnotation { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsReturnTypeAnnotation { +impl IntoFormat for rome_js_syntax::TsReturnTypeAnnotation { type Format = FormatOwnedWithRule< rome_js_syntax::TsReturnTypeAnnotation, FormatNodeRule, @@ -1281,7 +1281,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsFunctionBody { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsFunctionBody { +impl IntoFormat for rome_js_syntax::JsFunctionBody { type Format = FormatOwnedWithRule< rome_js_syntax::JsFunctionBody, FormatNodeRule, @@ -1293,7 +1293,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsSpread { FormatRefWithRule<'a, rome_js_syntax::JsSpread, FormatNodeRule>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsSpread { +impl IntoFormat for rome_js_syntax::JsSpread { type Format = FormatOwnedWithRule>; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -1306,7 +1306,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsArrayHole { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsArrayHole { +impl IntoFormat for rome_js_syntax::JsArrayHole { type Format = FormatOwnedWithRule< rome_js_syntax::JsArrayHole, FormatNodeRule, @@ -1321,7 +1321,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsReferenceIdentifier { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsReferenceIdentifier { +impl IntoFormat for rome_js_syntax::JsReferenceIdentifier { type Format = FormatOwnedWithRule< rome_js_syntax::JsReferenceIdentifier, FormatNodeRule, @@ -1336,7 +1336,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsPrivateName { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsPrivateName { +impl IntoFormat for rome_js_syntax::JsPrivateName { type Format = FormatOwnedWithRule< rome_js_syntax::JsPrivateName, FormatNodeRule, @@ -1351,7 +1351,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsLiteralMemberName { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsLiteralMemberName { +impl IntoFormat for rome_js_syntax::JsLiteralMemberName { type Format = FormatOwnedWithRule< rome_js_syntax::JsLiteralMemberName, FormatNodeRule, @@ -1366,7 +1366,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsComputedMemberName { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsComputedMemberName { +impl IntoFormat for rome_js_syntax::JsComputedMemberName { type Format = FormatOwnedWithRule< rome_js_syntax::JsComputedMemberName, FormatNodeRule, @@ -1381,7 +1381,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsPropertyObjectMember { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsPropertyObjectMember { +impl IntoFormat for rome_js_syntax::JsPropertyObjectMember { type Format = FormatOwnedWithRule< rome_js_syntax::JsPropertyObjectMember, FormatNodeRule, @@ -1396,7 +1396,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsMethodObjectMember { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsMethodObjectMember { +impl IntoFormat for rome_js_syntax::JsMethodObjectMember { type Format = FormatOwnedWithRule< rome_js_syntax::JsMethodObjectMember, FormatNodeRule, @@ -1411,7 +1411,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsGetterObjectMember { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsGetterObjectMember { +impl IntoFormat for rome_js_syntax::JsGetterObjectMember { type Format = FormatOwnedWithRule< rome_js_syntax::JsGetterObjectMember, FormatNodeRule, @@ -1426,7 +1426,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsSetterObjectMember { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsSetterObjectMember { +impl IntoFormat for rome_js_syntax::JsSetterObjectMember { type Format = FormatOwnedWithRule< rome_js_syntax::JsSetterObjectMember, FormatNodeRule, @@ -1441,7 +1441,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsShorthandPropertyObjectMember { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsShorthandPropertyObjectMember { +impl IntoFormat for rome_js_syntax::JsShorthandPropertyObjectMember { type Format = FormatOwnedWithRule< rome_js_syntax::JsShorthandPropertyObjectMember, FormatNodeRule, @@ -1456,7 +1456,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsExtendsClause { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsExtendsClause { +impl IntoFormat for rome_js_syntax::JsExtendsClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsExtendsClause, FormatNodeRule, @@ -1471,7 +1471,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsImplementsClause { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsImplementsClause { +impl IntoFormat for rome_js_syntax::TsImplementsClause { type Format = FormatOwnedWithRule< rome_js_syntax::TsImplementsClause, FormatNodeRule, @@ -1486,7 +1486,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsClassExportDefaultDeclaration { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsClassExportDefaultDeclaration { +impl IntoFormat for rome_js_syntax::JsClassExportDefaultDeclaration { type Format = FormatOwnedWithRule< rome_js_syntax::JsClassExportDefaultDeclaration, FormatNodeRule, @@ -1501,7 +1501,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsPrivateClassMemberName { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsPrivateClassMemberName { +impl IntoFormat for rome_js_syntax::JsPrivateClassMemberName { type Format = FormatOwnedWithRule< rome_js_syntax::JsPrivateClassMemberName, FormatNodeRule, @@ -1516,7 +1516,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsConstructorClassMember { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsConstructorClassMember { +impl IntoFormat for rome_js_syntax::JsConstructorClassMember { type Format = FormatOwnedWithRule< rome_js_syntax::JsConstructorClassMember, FormatNodeRule, @@ -1531,7 +1531,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsStaticInitializationBlockClassMember >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsStaticInitializationBlockClassMember { +impl IntoFormat for rome_js_syntax::JsStaticInitializationBlockClassMember { type Format = FormatOwnedWithRule< rome_js_syntax::JsStaticInitializationBlockClassMember, FormatNodeRule, @@ -1546,7 +1546,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsPropertyClassMember { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsPropertyClassMember { +impl IntoFormat for rome_js_syntax::JsPropertyClassMember { type Format = FormatOwnedWithRule< rome_js_syntax::JsPropertyClassMember, FormatNodeRule, @@ -1561,7 +1561,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsMethodClassMember { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsMethodClassMember { +impl IntoFormat for rome_js_syntax::JsMethodClassMember { type Format = FormatOwnedWithRule< rome_js_syntax::JsMethodClassMember, FormatNodeRule, @@ -1576,7 +1576,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsGetterClassMember { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsGetterClassMember { +impl IntoFormat for rome_js_syntax::JsGetterClassMember { type Format = FormatOwnedWithRule< rome_js_syntax::JsGetterClassMember, FormatNodeRule, @@ -1591,7 +1591,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsSetterClassMember { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsSetterClassMember { +impl IntoFormat for rome_js_syntax::JsSetterClassMember { type Format = FormatOwnedWithRule< rome_js_syntax::JsSetterClassMember, FormatNodeRule, @@ -1606,7 +1606,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsConstructorSignatureClassMember { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsConstructorSignatureClassMember { +impl IntoFormat for rome_js_syntax::TsConstructorSignatureClassMember { type Format = FormatOwnedWithRule< rome_js_syntax::TsConstructorSignatureClassMember, FormatNodeRule, @@ -1621,7 +1621,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsPropertySignatureClassMember { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsPropertySignatureClassMember { +impl IntoFormat for rome_js_syntax::TsPropertySignatureClassMember { type Format = FormatOwnedWithRule< rome_js_syntax::TsPropertySignatureClassMember, FormatNodeRule, @@ -1636,7 +1636,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsMethodSignatureClassMember { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsMethodSignatureClassMember { +impl IntoFormat for rome_js_syntax::TsMethodSignatureClassMember { type Format = FormatOwnedWithRule< rome_js_syntax::TsMethodSignatureClassMember, FormatNodeRule, @@ -1651,7 +1651,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsGetterSignatureClassMember { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsGetterSignatureClassMember { +impl IntoFormat for rome_js_syntax::TsGetterSignatureClassMember { type Format = FormatOwnedWithRule< rome_js_syntax::TsGetterSignatureClassMember, FormatNodeRule, @@ -1666,7 +1666,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsSetterSignatureClassMember { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsSetterSignatureClassMember { +impl IntoFormat for rome_js_syntax::TsSetterSignatureClassMember { type Format = FormatOwnedWithRule< rome_js_syntax::TsSetterSignatureClassMember, FormatNodeRule, @@ -1681,7 +1681,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsIndexSignatureClassMember { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsIndexSignatureClassMember { +impl IntoFormat for rome_js_syntax::TsIndexSignatureClassMember { type Format = FormatOwnedWithRule< rome_js_syntax::TsIndexSignatureClassMember, FormatNodeRule, @@ -1696,7 +1696,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsEmptyClassMember { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsEmptyClassMember { +impl IntoFormat for rome_js_syntax::JsEmptyClassMember { type Format = FormatOwnedWithRule< rome_js_syntax::JsEmptyClassMember, FormatNodeRule, @@ -1711,7 +1711,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsStaticModifier { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsStaticModifier { +impl IntoFormat for rome_js_syntax::JsStaticModifier { type Format = FormatOwnedWithRule< rome_js_syntax::JsStaticModifier, FormatNodeRule, @@ -1726,7 +1726,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsDeclareModifier { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsDeclareModifier { +impl IntoFormat for rome_js_syntax::TsDeclareModifier { type Format = FormatOwnedWithRule< rome_js_syntax::TsDeclareModifier, FormatNodeRule, @@ -1741,7 +1741,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsReadonlyModifier { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsReadonlyModifier { +impl IntoFormat for rome_js_syntax::TsReadonlyModifier { type Format = FormatOwnedWithRule< rome_js_syntax::TsReadonlyModifier, FormatNodeRule, @@ -1756,7 +1756,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAbstractModifier { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsAbstractModifier { +impl IntoFormat for rome_js_syntax::TsAbstractModifier { type Format = FormatOwnedWithRule< rome_js_syntax::TsAbstractModifier, FormatNodeRule, @@ -1771,7 +1771,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsOverrideModifier { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsOverrideModifier { +impl IntoFormat for rome_js_syntax::TsOverrideModifier { type Format = FormatOwnedWithRule< rome_js_syntax::TsOverrideModifier, FormatNodeRule, @@ -1786,7 +1786,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAccessibilityModifier { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsAccessibilityModifier { +impl IntoFormat for rome_js_syntax::TsAccessibilityModifier { type Format = FormatOwnedWithRule< rome_js_syntax::TsAccessibilityModifier, FormatNodeRule, @@ -1801,7 +1801,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsConstructorParameters { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsConstructorParameters { +impl IntoFormat for rome_js_syntax::JsConstructorParameters { type Format = FormatOwnedWithRule< rome_js_syntax::JsConstructorParameters, FormatNodeRule, @@ -1816,7 +1816,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsRestParameter { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsRestParameter { +impl IntoFormat for rome_js_syntax::JsRestParameter { type Format = FormatOwnedWithRule< rome_js_syntax::JsRestParameter, FormatNodeRule, @@ -1831,7 +1831,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsPropertyParameter { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsPropertyParameter { +impl IntoFormat for rome_js_syntax::TsPropertyParameter { type Format = FormatOwnedWithRule< rome_js_syntax::TsPropertyParameter, FormatNodeRule, @@ -1846,7 +1846,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsInitializerClause { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsInitializerClause { +impl IntoFormat for rome_js_syntax::JsInitializerClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsInitializerClause, FormatNodeRule, @@ -1861,7 +1861,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsOptionalPropertyAnnotation { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsOptionalPropertyAnnotation { +impl IntoFormat for rome_js_syntax::TsOptionalPropertyAnnotation { type Format = FormatOwnedWithRule< rome_js_syntax::TsOptionalPropertyAnnotation, FormatNodeRule, @@ -1876,7 +1876,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsDefinitePropertyAnnotation { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsDefinitePropertyAnnotation { +impl IntoFormat for rome_js_syntax::TsDefinitePropertyAnnotation { type Format = FormatOwnedWithRule< rome_js_syntax::TsDefinitePropertyAnnotation, FormatNodeRule, @@ -1891,7 +1891,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsIndexSignatureParameter { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsIndexSignatureParameter { +impl IntoFormat for rome_js_syntax::TsIndexSignatureParameter { type Format = FormatOwnedWithRule< rome_js_syntax::TsIndexSignatureParameter, FormatNodeRule, @@ -1906,7 +1906,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsIdentifierAssignment { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsIdentifierAssignment { +impl IntoFormat for rome_js_syntax::JsIdentifierAssignment { type Format = FormatOwnedWithRule< rome_js_syntax::JsIdentifierAssignment, FormatNodeRule, @@ -1921,7 +1921,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsStaticMemberAssignment { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsStaticMemberAssignment { +impl IntoFormat for rome_js_syntax::JsStaticMemberAssignment { type Format = FormatOwnedWithRule< rome_js_syntax::JsStaticMemberAssignment, FormatNodeRule, @@ -1936,7 +1936,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsComputedMemberAssignment { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsComputedMemberAssignment { +impl IntoFormat for rome_js_syntax::JsComputedMemberAssignment { type Format = FormatOwnedWithRule< rome_js_syntax::JsComputedMemberAssignment, FormatNodeRule, @@ -1951,7 +1951,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsParenthesizedAssignment { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsParenthesizedAssignment { +impl IntoFormat for rome_js_syntax::JsParenthesizedAssignment { type Format = FormatOwnedWithRule< rome_js_syntax::JsParenthesizedAssignment, FormatNodeRule, @@ -1966,7 +1966,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsNonNullAssertionAssignment { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsNonNullAssertionAssignment { +impl IntoFormat for rome_js_syntax::TsNonNullAssertionAssignment { type Format = FormatOwnedWithRule< rome_js_syntax::TsNonNullAssertionAssignment, FormatNodeRule, @@ -1981,7 +1981,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAsAssignment { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsAsAssignment { +impl IntoFormat for rome_js_syntax::TsAsAssignment { type Format = FormatOwnedWithRule< rome_js_syntax::TsAsAssignment, FormatNodeRule, @@ -1996,7 +1996,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeAssertionAssignment { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsTypeAssertionAssignment { +impl IntoFormat for rome_js_syntax::TsTypeAssertionAssignment { type Format = FormatOwnedWithRule< rome_js_syntax::TsTypeAssertionAssignment, FormatNodeRule, @@ -2011,7 +2011,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAssignmentWithDefault { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAssignmentWithDefault { +impl IntoFormat for rome_js_syntax::JsAssignmentWithDefault { type Format = FormatOwnedWithRule< rome_js_syntax::JsAssignmentWithDefault, FormatNodeRule, @@ -2026,7 +2026,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsArrayAssignmentPattern { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsArrayAssignmentPattern { +impl IntoFormat for rome_js_syntax::JsArrayAssignmentPattern { type Format = FormatOwnedWithRule< rome_js_syntax::JsArrayAssignmentPattern, FormatNodeRule, @@ -2041,7 +2041,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectAssignmentPattern { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsObjectAssignmentPattern { +impl IntoFormat for rome_js_syntax::JsObjectAssignmentPattern { type Format = FormatOwnedWithRule< rome_js_syntax::JsObjectAssignmentPattern, FormatNodeRule, @@ -2056,7 +2056,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsArrayAssignmentPatternRestElement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsArrayAssignmentPatternRestElement { +impl IntoFormat for rome_js_syntax::JsArrayAssignmentPatternRestElement { type Format = FormatOwnedWithRule< rome_js_syntax::JsArrayAssignmentPatternRestElement, FormatNodeRule, @@ -2071,7 +2071,9 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectAssignmentPatternShorthandProp >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsObjectAssignmentPatternShorthandProperty { +impl IntoFormat + for rome_js_syntax::JsObjectAssignmentPatternShorthandProperty +{ type Format = FormatOwnedWithRule< rome_js_syntax::JsObjectAssignmentPatternShorthandProperty, FormatNodeRule, @@ -2086,7 +2088,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectAssignmentPatternProperty { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsObjectAssignmentPatternProperty { +impl IntoFormat for rome_js_syntax::JsObjectAssignmentPatternProperty { type Format = FormatOwnedWithRule< rome_js_syntax::JsObjectAssignmentPatternProperty, FormatNodeRule, @@ -2101,7 +2103,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectAssignmentPatternRest { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsObjectAssignmentPatternRest { +impl IntoFormat for rome_js_syntax::JsObjectAssignmentPatternRest { type Format = FormatOwnedWithRule< rome_js_syntax::JsObjectAssignmentPatternRest, FormatNodeRule, @@ -2116,7 +2118,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsIdentifierBinding { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsIdentifierBinding { +impl IntoFormat for rome_js_syntax::JsIdentifierBinding { type Format = FormatOwnedWithRule< rome_js_syntax::JsIdentifierBinding, FormatNodeRule, @@ -2131,7 +2133,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsBindingPatternWithDefault { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsBindingPatternWithDefault { +impl IntoFormat for rome_js_syntax::JsBindingPatternWithDefault { type Format = FormatOwnedWithRule< rome_js_syntax::JsBindingPatternWithDefault, FormatNodeRule, @@ -2146,7 +2148,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsArrayBindingPattern { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsArrayBindingPattern { +impl IntoFormat for rome_js_syntax::JsArrayBindingPattern { type Format = FormatOwnedWithRule< rome_js_syntax::JsArrayBindingPattern, FormatNodeRule, @@ -2161,7 +2163,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectBindingPattern { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsObjectBindingPattern { +impl IntoFormat for rome_js_syntax::JsObjectBindingPattern { type Format = FormatOwnedWithRule< rome_js_syntax::JsObjectBindingPattern, FormatNodeRule, @@ -2176,7 +2178,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsArrayBindingPatternRestElement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsArrayBindingPatternRestElement { +impl IntoFormat for rome_js_syntax::JsArrayBindingPatternRestElement { type Format = FormatOwnedWithRule< rome_js_syntax::JsArrayBindingPatternRestElement, FormatNodeRule, @@ -2191,7 +2193,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectBindingPatternProperty { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsObjectBindingPatternProperty { +impl IntoFormat for rome_js_syntax::JsObjectBindingPatternProperty { type Format = FormatOwnedWithRule< rome_js_syntax::JsObjectBindingPatternProperty, FormatNodeRule, @@ -2206,7 +2208,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectBindingPatternRest { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsObjectBindingPatternRest { +impl IntoFormat for rome_js_syntax::JsObjectBindingPatternRest { type Format = FormatOwnedWithRule< rome_js_syntax::JsObjectBindingPatternRest, FormatNodeRule, @@ -2221,7 +2223,9 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectBindingPatternShorthandPropert >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsObjectBindingPatternShorthandProperty { +impl IntoFormat + for rome_js_syntax::JsObjectBindingPatternShorthandProperty +{ type Format = FormatOwnedWithRule< rome_js_syntax::JsObjectBindingPatternShorthandProperty, FormatNodeRule, @@ -2236,7 +2240,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsStringLiteralExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsStringLiteralExpression { +impl IntoFormat for rome_js_syntax::JsStringLiteralExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsStringLiteralExpression, FormatNodeRule, @@ -2251,7 +2255,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsNumberLiteralExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsNumberLiteralExpression { +impl IntoFormat for rome_js_syntax::JsNumberLiteralExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsNumberLiteralExpression, FormatNodeRule, @@ -2266,7 +2270,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsBigIntLiteralExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsBigIntLiteralExpression { +impl IntoFormat for rome_js_syntax::JsBigIntLiteralExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsBigIntLiteralExpression, FormatNodeRule, @@ -2281,7 +2285,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsBooleanLiteralExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsBooleanLiteralExpression { +impl IntoFormat for rome_js_syntax::JsBooleanLiteralExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsBooleanLiteralExpression, FormatNodeRule, @@ -2296,7 +2300,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsNullLiteralExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsNullLiteralExpression { +impl IntoFormat for rome_js_syntax::JsNullLiteralExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsNullLiteralExpression, FormatNodeRule, @@ -2311,7 +2315,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsRegexLiteralExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsRegexLiteralExpression { +impl IntoFormat for rome_js_syntax::JsRegexLiteralExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsRegexLiteralExpression, FormatNodeRule, @@ -2326,7 +2330,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsVariableDeclarationClause { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsVariableDeclarationClause { +impl IntoFormat for rome_js_syntax::JsVariableDeclarationClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsVariableDeclarationClause, FormatNodeRule, @@ -2341,7 +2345,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsDefiniteVariableAnnotation { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsDefiniteVariableAnnotation { +impl IntoFormat for rome_js_syntax::TsDefiniteVariableAnnotation { type Format = FormatOwnedWithRule< rome_js_syntax::TsDefiniteVariableAnnotation, FormatNodeRule, @@ -2353,7 +2357,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsExport { FormatRefWithRule<'a, rome_js_syntax::JsExport, FormatNodeRule>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsExport { +impl IntoFormat for rome_js_syntax::JsExport { type Format = FormatOwnedWithRule>; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -2363,7 +2367,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsImport { FormatRefWithRule<'a, rome_js_syntax::JsImport, FormatNodeRule>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsImport { +impl IntoFormat for rome_js_syntax::JsImport { type Format = FormatOwnedWithRule>; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -2376,7 +2380,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsImportBareClause { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsImportBareClause { +impl IntoFormat for rome_js_syntax::JsImportBareClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsImportBareClause, FormatNodeRule, @@ -2391,7 +2395,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsImportNamedClause { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsImportNamedClause { +impl IntoFormat for rome_js_syntax::JsImportNamedClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsImportNamedClause, FormatNodeRule, @@ -2406,7 +2410,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsImportDefaultClause { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsImportDefaultClause { +impl IntoFormat for rome_js_syntax::JsImportDefaultClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsImportDefaultClause, FormatNodeRule, @@ -2421,7 +2425,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsImportNamespaceClause { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsImportNamespaceClause { +impl IntoFormat for rome_js_syntax::JsImportNamespaceClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsImportNamespaceClause, FormatNodeRule, @@ -2436,7 +2440,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsModuleSource { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsModuleSource { +impl IntoFormat for rome_js_syntax::JsModuleSource { type Format = FormatOwnedWithRule< rome_js_syntax::JsModuleSource, FormatNodeRule, @@ -2451,7 +2455,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsImportAssertion { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsImportAssertion { +impl IntoFormat for rome_js_syntax::JsImportAssertion { type Format = FormatOwnedWithRule< rome_js_syntax::JsImportAssertion, FormatNodeRule, @@ -2466,7 +2470,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsDefaultImportSpecifier { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsDefaultImportSpecifier { +impl IntoFormat for rome_js_syntax::JsDefaultImportSpecifier { type Format = FormatOwnedWithRule< rome_js_syntax::JsDefaultImportSpecifier, FormatNodeRule, @@ -2481,7 +2485,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsNamedImportSpecifiers { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsNamedImportSpecifiers { +impl IntoFormat for rome_js_syntax::JsNamedImportSpecifiers { type Format = FormatOwnedWithRule< rome_js_syntax::JsNamedImportSpecifiers, FormatNodeRule, @@ -2496,7 +2500,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsNamespaceImportSpecifier { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsNamespaceImportSpecifier { +impl IntoFormat for rome_js_syntax::JsNamespaceImportSpecifier { type Format = FormatOwnedWithRule< rome_js_syntax::JsNamespaceImportSpecifier, FormatNodeRule, @@ -2511,7 +2515,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsShorthandNamedImportSpecifier { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsShorthandNamedImportSpecifier { +impl IntoFormat for rome_js_syntax::JsShorthandNamedImportSpecifier { type Format = FormatOwnedWithRule< rome_js_syntax::JsShorthandNamedImportSpecifier, FormatNodeRule, @@ -2526,7 +2530,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsNamedImportSpecifier { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsNamedImportSpecifier { +impl IntoFormat for rome_js_syntax::JsNamedImportSpecifier { type Format = FormatOwnedWithRule< rome_js_syntax::JsNamedImportSpecifier, FormatNodeRule, @@ -2541,7 +2545,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsLiteralExportName { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsLiteralExportName { +impl IntoFormat for rome_js_syntax::JsLiteralExportName { type Format = FormatOwnedWithRule< rome_js_syntax::JsLiteralExportName, FormatNodeRule, @@ -2556,7 +2560,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsImportAssertionEntry { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsImportAssertionEntry { +impl IntoFormat for rome_js_syntax::JsImportAssertionEntry { type Format = FormatOwnedWithRule< rome_js_syntax::JsImportAssertionEntry, FormatNodeRule, @@ -2571,7 +2575,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsExportDefaultDeclarationClause { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsExportDefaultDeclarationClause { +impl IntoFormat for rome_js_syntax::JsExportDefaultDeclarationClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsExportDefaultDeclarationClause, FormatNodeRule, @@ -2586,7 +2590,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsExportDefaultExpressionClause { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsExportDefaultExpressionClause { +impl IntoFormat for rome_js_syntax::JsExportDefaultExpressionClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsExportDefaultExpressionClause, FormatNodeRule, @@ -2601,7 +2605,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsExportNamedClause { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsExportNamedClause { +impl IntoFormat for rome_js_syntax::JsExportNamedClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsExportNamedClause, FormatNodeRule, @@ -2616,7 +2620,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsExportFromClause { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsExportFromClause { +impl IntoFormat for rome_js_syntax::JsExportFromClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsExportFromClause, FormatNodeRule, @@ -2631,7 +2635,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsExportNamedFromClause { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsExportNamedFromClause { +impl IntoFormat for rome_js_syntax::JsExportNamedFromClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsExportNamedFromClause, FormatNodeRule, @@ -2646,7 +2650,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsExportAsNamespaceClause { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsExportAsNamespaceClause { +impl IntoFormat for rome_js_syntax::TsExportAsNamespaceClause { type Format = FormatOwnedWithRule< rome_js_syntax::TsExportAsNamespaceClause, FormatNodeRule, @@ -2661,7 +2665,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsExportAssignmentClause { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsExportAssignmentClause { +impl IntoFormat for rome_js_syntax::TsExportAssignmentClause { type Format = FormatOwnedWithRule< rome_js_syntax::TsExportAssignmentClause, FormatNodeRule, @@ -2676,7 +2680,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsExportDeclareClause { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsExportDeclareClause { +impl IntoFormat for rome_js_syntax::TsExportDeclareClause { type Format = FormatOwnedWithRule< rome_js_syntax::TsExportDeclareClause, FormatNodeRule, @@ -2691,7 +2695,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsFunctionExportDefaultDeclaration { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsFunctionExportDefaultDeclaration { +impl IntoFormat for rome_js_syntax::JsFunctionExportDefaultDeclaration { type Format = FormatOwnedWithRule< rome_js_syntax::JsFunctionExportDefaultDeclaration, FormatNodeRule, @@ -2706,7 +2710,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsExportNamedShorthandSpecifier { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsExportNamedShorthandSpecifier { +impl IntoFormat for rome_js_syntax::JsExportNamedShorthandSpecifier { type Format = FormatOwnedWithRule< rome_js_syntax::JsExportNamedShorthandSpecifier, FormatNodeRule, @@ -2721,7 +2725,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsExportNamedSpecifier { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsExportNamedSpecifier { +impl IntoFormat for rome_js_syntax::JsExportNamedSpecifier { type Format = FormatOwnedWithRule< rome_js_syntax::JsExportNamedSpecifier, FormatNodeRule, @@ -2736,7 +2740,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsExportAsClause { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsExportAsClause { +impl IntoFormat for rome_js_syntax::JsExportAsClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsExportAsClause, FormatNodeRule, @@ -2751,7 +2755,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsExportNamedFromSpecifier { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsExportNamedFromSpecifier { +impl IntoFormat for rome_js_syntax::JsExportNamedFromSpecifier { type Format = FormatOwnedWithRule< rome_js_syntax::JsExportNamedFromSpecifier, FormatNodeRule, @@ -2763,7 +2767,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsName { FormatRefWithRule<'a, rome_js_syntax::JsName, FormatNodeRule>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsName { +impl IntoFormat for rome_js_syntax::JsName { type Format = FormatOwnedWithRule>; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -2776,7 +2780,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsFormalParameter { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsFormalParameter { +impl IntoFormat for rome_js_syntax::JsFormalParameter { type Format = FormatOwnedWithRule< rome_js_syntax::JsFormalParameter, FormatNodeRule, @@ -2791,7 +2795,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsThisParameter { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsThisParameter { +impl IntoFormat for rome_js_syntax::TsThisParameter { type Format = FormatOwnedWithRule< rome_js_syntax::TsThisParameter, FormatNodeRule, @@ -2803,7 +2807,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyType { FormatRefWithRule<'a, rome_js_syntax::TsAnyType, FormatNodeRule>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsAnyType { +impl IntoFormat for rome_js_syntax::TsAnyType { type Format = FormatOwnedWithRule>; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -2816,7 +2820,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsUnknownType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsUnknownType { +impl IntoFormat for rome_js_syntax::TsUnknownType { type Format = FormatOwnedWithRule< rome_js_syntax::TsUnknownType, FormatNodeRule, @@ -2831,7 +2835,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsNumberType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsNumberType { +impl IntoFormat for rome_js_syntax::TsNumberType { type Format = FormatOwnedWithRule< rome_js_syntax::TsNumberType, FormatNodeRule, @@ -2846,7 +2850,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsBooleanType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsBooleanType { +impl IntoFormat for rome_js_syntax::TsBooleanType { type Format = FormatOwnedWithRule< rome_js_syntax::TsBooleanType, FormatNodeRule, @@ -2861,7 +2865,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsBigintType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsBigintType { +impl IntoFormat for rome_js_syntax::TsBigintType { type Format = FormatOwnedWithRule< rome_js_syntax::TsBigintType, FormatNodeRule, @@ -2876,7 +2880,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsStringType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsStringType { +impl IntoFormat for rome_js_syntax::TsStringType { type Format = FormatOwnedWithRule< rome_js_syntax::TsStringType, FormatNodeRule, @@ -2891,7 +2895,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsSymbolType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsSymbolType { +impl IntoFormat for rome_js_syntax::TsSymbolType { type Format = FormatOwnedWithRule< rome_js_syntax::TsSymbolType, FormatNodeRule, @@ -2906,7 +2910,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsVoidType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsVoidType { +impl IntoFormat for rome_js_syntax::TsVoidType { type Format = FormatOwnedWithRule>; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -2919,7 +2923,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsUndefinedType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsUndefinedType { +impl IntoFormat for rome_js_syntax::TsUndefinedType { type Format = FormatOwnedWithRule< rome_js_syntax::TsUndefinedType, FormatNodeRule, @@ -2934,7 +2938,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsNeverType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsNeverType { +impl IntoFormat for rome_js_syntax::TsNeverType { type Format = FormatOwnedWithRule< rome_js_syntax::TsNeverType, FormatNodeRule, @@ -2949,7 +2953,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsParenthesizedType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsParenthesizedType { +impl IntoFormat for rome_js_syntax::TsParenthesizedType { type Format = FormatOwnedWithRule< rome_js_syntax::TsParenthesizedType, FormatNodeRule, @@ -2964,7 +2968,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsReferenceType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsReferenceType { +impl IntoFormat for rome_js_syntax::TsReferenceType { type Format = FormatOwnedWithRule< rome_js_syntax::TsReferenceType, FormatNodeRule, @@ -2979,7 +2983,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsArrayType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsArrayType { +impl IntoFormat for rome_js_syntax::TsArrayType { type Format = FormatOwnedWithRule< rome_js_syntax::TsArrayType, FormatNodeRule, @@ -2994,7 +2998,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTupleType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsTupleType { +impl IntoFormat for rome_js_syntax::TsTupleType { type Format = FormatOwnedWithRule< rome_js_syntax::TsTupleType, FormatNodeRule, @@ -3009,7 +3013,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeofType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsTypeofType { +impl IntoFormat for rome_js_syntax::TsTypeofType { type Format = FormatOwnedWithRule< rome_js_syntax::TsTypeofType, FormatNodeRule, @@ -3024,7 +3028,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsImportType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsImportType { +impl IntoFormat for rome_js_syntax::TsImportType { type Format = FormatOwnedWithRule< rome_js_syntax::TsImportType, FormatNodeRule, @@ -3039,7 +3043,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeOperatorType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsTypeOperatorType { +impl IntoFormat for rome_js_syntax::TsTypeOperatorType { type Format = FormatOwnedWithRule< rome_js_syntax::TsTypeOperatorType, FormatNodeRule, @@ -3054,7 +3058,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsIndexedAccessType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsIndexedAccessType { +impl IntoFormat for rome_js_syntax::TsIndexedAccessType { type Format = FormatOwnedWithRule< rome_js_syntax::TsIndexedAccessType, FormatNodeRule, @@ -3069,7 +3073,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsMappedType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsMappedType { +impl IntoFormat for rome_js_syntax::TsMappedType { type Format = FormatOwnedWithRule< rome_js_syntax::TsMappedType, FormatNodeRule, @@ -3084,7 +3088,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsObjectType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsObjectType { +impl IntoFormat for rome_js_syntax::TsObjectType { type Format = FormatOwnedWithRule< rome_js_syntax::TsObjectType, FormatNodeRule, @@ -3099,7 +3103,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsNonPrimitiveType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsNonPrimitiveType { +impl IntoFormat for rome_js_syntax::TsNonPrimitiveType { type Format = FormatOwnedWithRule< rome_js_syntax::TsNonPrimitiveType, FormatNodeRule, @@ -3114,7 +3118,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsThisType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsThisType { +impl IntoFormat for rome_js_syntax::TsThisType { type Format = FormatOwnedWithRule>; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -3127,7 +3131,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsNumberLiteralType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsNumberLiteralType { +impl IntoFormat for rome_js_syntax::TsNumberLiteralType { type Format = FormatOwnedWithRule< rome_js_syntax::TsNumberLiteralType, FormatNodeRule, @@ -3142,7 +3146,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsBigIntLiteralType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsBigIntLiteralType { +impl IntoFormat for rome_js_syntax::TsBigIntLiteralType { type Format = FormatOwnedWithRule< rome_js_syntax::TsBigIntLiteralType, FormatNodeRule, @@ -3157,7 +3161,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsStringLiteralType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsStringLiteralType { +impl IntoFormat for rome_js_syntax::TsStringLiteralType { type Format = FormatOwnedWithRule< rome_js_syntax::TsStringLiteralType, FormatNodeRule, @@ -3172,7 +3176,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsNullLiteralType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsNullLiteralType { +impl IntoFormat for rome_js_syntax::TsNullLiteralType { type Format = FormatOwnedWithRule< rome_js_syntax::TsNullLiteralType, FormatNodeRule, @@ -3187,7 +3191,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsBooleanLiteralType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsBooleanLiteralType { +impl IntoFormat for rome_js_syntax::TsBooleanLiteralType { type Format = FormatOwnedWithRule< rome_js_syntax::TsBooleanLiteralType, FormatNodeRule, @@ -3202,7 +3206,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTemplateLiteralType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsTemplateLiteralType { +impl IntoFormat for rome_js_syntax::TsTemplateLiteralType { type Format = FormatOwnedWithRule< rome_js_syntax::TsTemplateLiteralType, FormatNodeRule, @@ -3217,7 +3221,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsInferType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsInferType { +impl IntoFormat for rome_js_syntax::TsInferType { type Format = FormatOwnedWithRule< rome_js_syntax::TsInferType, FormatNodeRule, @@ -3232,7 +3236,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsIntersectionType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsIntersectionType { +impl IntoFormat for rome_js_syntax::TsIntersectionType { type Format = FormatOwnedWithRule< rome_js_syntax::TsIntersectionType, FormatNodeRule, @@ -3247,7 +3251,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsUnionType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsUnionType { +impl IntoFormat for rome_js_syntax::TsUnionType { type Format = FormatOwnedWithRule< rome_js_syntax::TsUnionType, FormatNodeRule, @@ -3262,7 +3266,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsFunctionType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsFunctionType { +impl IntoFormat for rome_js_syntax::TsFunctionType { type Format = FormatOwnedWithRule< rome_js_syntax::TsFunctionType, FormatNodeRule, @@ -3277,7 +3281,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsConstructorType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsConstructorType { +impl IntoFormat for rome_js_syntax::TsConstructorType { type Format = FormatOwnedWithRule< rome_js_syntax::TsConstructorType, FormatNodeRule, @@ -3292,7 +3296,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsConditionalType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsConditionalType { +impl IntoFormat for rome_js_syntax::TsConditionalType { type Format = FormatOwnedWithRule< rome_js_syntax::TsConditionalType, FormatNodeRule, @@ -3307,7 +3311,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsIdentifierBinding { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsIdentifierBinding { +impl IntoFormat for rome_js_syntax::TsIdentifierBinding { type Format = FormatOwnedWithRule< rome_js_syntax::TsIdentifierBinding, FormatNodeRule, @@ -3322,7 +3326,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsEnumMember { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsEnumMember { +impl IntoFormat for rome_js_syntax::TsEnumMember { type Format = FormatOwnedWithRule< rome_js_syntax::TsEnumMember, FormatNodeRule, @@ -3337,7 +3341,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsExternalModuleReference { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsExternalModuleReference { +impl IntoFormat for rome_js_syntax::TsExternalModuleReference { type Format = FormatOwnedWithRule< rome_js_syntax::TsExternalModuleReference, FormatNodeRule, @@ -3352,7 +3356,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsModuleBlock { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsModuleBlock { +impl IntoFormat for rome_js_syntax::TsModuleBlock { type Format = FormatOwnedWithRule< rome_js_syntax::TsModuleBlock, FormatNodeRule, @@ -3367,7 +3371,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsQualifiedModuleName { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsQualifiedModuleName { +impl IntoFormat for rome_js_syntax::TsQualifiedModuleName { type Format = FormatOwnedWithRule< rome_js_syntax::TsQualifiedModuleName, FormatNodeRule, @@ -3382,7 +3386,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsEmptyExternalModuleDeclarationBody { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsEmptyExternalModuleDeclarationBody { +impl IntoFormat for rome_js_syntax::TsEmptyExternalModuleDeclarationBody { type Format = FormatOwnedWithRule< rome_js_syntax::TsEmptyExternalModuleDeclarationBody, FormatNodeRule, @@ -3397,7 +3401,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeParameterName { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsTypeParameterName { +impl IntoFormat for rome_js_syntax::TsTypeParameterName { type Format = FormatOwnedWithRule< rome_js_syntax::TsTypeParameterName, FormatNodeRule, @@ -3412,7 +3416,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsPredicateReturnType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsPredicateReturnType { +impl IntoFormat for rome_js_syntax::TsPredicateReturnType { type Format = FormatOwnedWithRule< rome_js_syntax::TsPredicateReturnType, FormatNodeRule, @@ -3427,7 +3431,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAssertsReturnType { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsAssertsReturnType { +impl IntoFormat for rome_js_syntax::TsAssertsReturnType { type Format = FormatOwnedWithRule< rome_js_syntax::TsAssertsReturnType, FormatNodeRule, @@ -3442,7 +3446,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAssertsCondition { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsAssertsCondition { +impl IntoFormat for rome_js_syntax::TsAssertsCondition { type Format = FormatOwnedWithRule< rome_js_syntax::TsAssertsCondition, FormatNodeRule, @@ -3457,7 +3461,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeParameter { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsTypeParameter { +impl IntoFormat for rome_js_syntax::TsTypeParameter { type Format = FormatOwnedWithRule< rome_js_syntax::TsTypeParameter, FormatNodeRule, @@ -3472,7 +3476,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeConstraintClause { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsTypeConstraintClause { +impl IntoFormat for rome_js_syntax::TsTypeConstraintClause { type Format = FormatOwnedWithRule< rome_js_syntax::TsTypeConstraintClause, FormatNodeRule, @@ -3487,7 +3491,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsDefaultTypeClause { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsDefaultTypeClause { +impl IntoFormat for rome_js_syntax::TsDefaultTypeClause { type Format = FormatOwnedWithRule< rome_js_syntax::TsDefaultTypeClause, FormatNodeRule, @@ -3502,7 +3506,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsExtendsClause { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsExtendsClause { +impl IntoFormat for rome_js_syntax::TsExtendsClause { type Format = FormatOwnedWithRule< rome_js_syntax::TsExtendsClause, FormatNodeRule, @@ -3517,7 +3521,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsNameWithTypeArguments { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsNameWithTypeArguments { +impl IntoFormat for rome_js_syntax::TsNameWithTypeArguments { type Format = FormatOwnedWithRule< rome_js_syntax::TsNameWithTypeArguments, FormatNodeRule, @@ -3532,7 +3536,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsCallSignatureTypeMember { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsCallSignatureTypeMember { +impl IntoFormat for rome_js_syntax::TsCallSignatureTypeMember { type Format = FormatOwnedWithRule< rome_js_syntax::TsCallSignatureTypeMember, FormatNodeRule, @@ -3547,7 +3551,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsPropertySignatureTypeMember { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsPropertySignatureTypeMember { +impl IntoFormat for rome_js_syntax::TsPropertySignatureTypeMember { type Format = FormatOwnedWithRule< rome_js_syntax::TsPropertySignatureTypeMember, FormatNodeRule, @@ -3562,7 +3566,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsConstructSignatureTypeMember { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsConstructSignatureTypeMember { +impl IntoFormat for rome_js_syntax::TsConstructSignatureTypeMember { type Format = FormatOwnedWithRule< rome_js_syntax::TsConstructSignatureTypeMember, FormatNodeRule, @@ -3577,7 +3581,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsMethodSignatureTypeMember { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsMethodSignatureTypeMember { +impl IntoFormat for rome_js_syntax::TsMethodSignatureTypeMember { type Format = FormatOwnedWithRule< rome_js_syntax::TsMethodSignatureTypeMember, FormatNodeRule, @@ -3592,7 +3596,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsGetterSignatureTypeMember { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsGetterSignatureTypeMember { +impl IntoFormat for rome_js_syntax::TsGetterSignatureTypeMember { type Format = FormatOwnedWithRule< rome_js_syntax::TsGetterSignatureTypeMember, FormatNodeRule, @@ -3607,7 +3611,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsSetterSignatureTypeMember { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsSetterSignatureTypeMember { +impl IntoFormat for rome_js_syntax::TsSetterSignatureTypeMember { type Format = FormatOwnedWithRule< rome_js_syntax::TsSetterSignatureTypeMember, FormatNodeRule, @@ -3622,7 +3626,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsIndexSignatureTypeMember { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsIndexSignatureTypeMember { +impl IntoFormat for rome_js_syntax::TsIndexSignatureTypeMember { type Format = FormatOwnedWithRule< rome_js_syntax::TsIndexSignatureTypeMember, FormatNodeRule, @@ -3637,7 +3641,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsMappedTypeReadonlyModifierClause { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsMappedTypeReadonlyModifierClause { +impl IntoFormat for rome_js_syntax::TsMappedTypeReadonlyModifierClause { type Format = FormatOwnedWithRule< rome_js_syntax::TsMappedTypeReadonlyModifierClause, FormatNodeRule, @@ -3652,7 +3656,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsMappedTypeAsClause { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsMappedTypeAsClause { +impl IntoFormat for rome_js_syntax::TsMappedTypeAsClause { type Format = FormatOwnedWithRule< rome_js_syntax::TsMappedTypeAsClause, FormatNodeRule, @@ -3667,7 +3671,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsMappedTypeOptionalModifierClause { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsMappedTypeOptionalModifierClause { +impl IntoFormat for rome_js_syntax::TsMappedTypeOptionalModifierClause { type Format = FormatOwnedWithRule< rome_js_syntax::TsMappedTypeOptionalModifierClause, FormatNodeRule, @@ -3682,7 +3686,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsImportTypeQualifier { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsImportTypeQualifier { +impl IntoFormat for rome_js_syntax::TsImportTypeQualifier { type Format = FormatOwnedWithRule< rome_js_syntax::TsImportTypeQualifier, FormatNodeRule, @@ -3697,7 +3701,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsNamedTupleTypeElement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsNamedTupleTypeElement { +impl IntoFormat for rome_js_syntax::TsNamedTupleTypeElement { type Format = FormatOwnedWithRule< rome_js_syntax::TsNamedTupleTypeElement, FormatNodeRule, @@ -3712,7 +3716,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsRestTupleTypeElement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsRestTupleTypeElement { +impl IntoFormat for rome_js_syntax::TsRestTupleTypeElement { type Format = FormatOwnedWithRule< rome_js_syntax::TsRestTupleTypeElement, FormatNodeRule, @@ -3727,7 +3731,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsOptionalTupleTypeElement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsOptionalTupleTypeElement { +impl IntoFormat for rome_js_syntax::TsOptionalTupleTypeElement { type Format = FormatOwnedWithRule< rome_js_syntax::TsOptionalTupleTypeElement, FormatNodeRule, @@ -3742,7 +3746,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTemplateChunkElement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsTemplateChunkElement { +impl IntoFormat for rome_js_syntax::TsTemplateChunkElement { type Format = FormatOwnedWithRule< rome_js_syntax::TsTemplateChunkElement, FormatNodeRule, @@ -3757,7 +3761,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTemplateElement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsTemplateElement { +impl IntoFormat for rome_js_syntax::TsTemplateElement { type Format = FormatOwnedWithRule< rome_js_syntax::TsTemplateElement, FormatNodeRule, @@ -3772,7 +3776,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsQualifiedName { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsQualifiedName { +impl IntoFormat for rome_js_syntax::TsQualifiedName { type Format = FormatOwnedWithRule< rome_js_syntax::TsQualifiedName, FormatNodeRule, @@ -3787,7 +3791,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxElement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsxElement { +impl IntoFormat for rome_js_syntax::JsxElement { type Format = FormatOwnedWithRule>; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -3800,7 +3804,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxSelfClosingElement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsxSelfClosingElement { +impl IntoFormat for rome_js_syntax::JsxSelfClosingElement { type Format = FormatOwnedWithRule< rome_js_syntax::JsxSelfClosingElement, FormatNodeRule, @@ -3815,7 +3819,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxFragment { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsxFragment { +impl IntoFormat for rome_js_syntax::JsxFragment { type Format = FormatOwnedWithRule< rome_js_syntax::JsxFragment, FormatNodeRule, @@ -3830,7 +3834,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxOpeningElement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsxOpeningElement { +impl IntoFormat for rome_js_syntax::JsxOpeningElement { type Format = FormatOwnedWithRule< rome_js_syntax::JsxOpeningElement, FormatNodeRule, @@ -3845,7 +3849,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxClosingElement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsxClosingElement { +impl IntoFormat for rome_js_syntax::JsxClosingElement { type Format = FormatOwnedWithRule< rome_js_syntax::JsxClosingElement, FormatNodeRule, @@ -3860,7 +3864,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxOpeningFragment { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsxOpeningFragment { +impl IntoFormat for rome_js_syntax::JsxOpeningFragment { type Format = FormatOwnedWithRule< rome_js_syntax::JsxOpeningFragment, FormatNodeRule, @@ -3875,7 +3879,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxClosingFragment { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsxClosingFragment { +impl IntoFormat for rome_js_syntax::JsxClosingFragment { type Format = FormatOwnedWithRule< rome_js_syntax::JsxClosingFragment, FormatNodeRule, @@ -3887,7 +3891,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxName { FormatRefWithRule<'a, rome_js_syntax::JsxName, FormatNodeRule>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsxName { +impl IntoFormat for rome_js_syntax::JsxName { type Format = FormatOwnedWithRule>; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -3900,7 +3904,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxReferenceIdentifier { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsxReferenceIdentifier { +impl IntoFormat for rome_js_syntax::JsxReferenceIdentifier { type Format = FormatOwnedWithRule< rome_js_syntax::JsxReferenceIdentifier, FormatNodeRule, @@ -3915,7 +3919,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxNamespaceName { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsxNamespaceName { +impl IntoFormat for rome_js_syntax::JsxNamespaceName { type Format = FormatOwnedWithRule< rome_js_syntax::JsxNamespaceName, FormatNodeRule, @@ -3930,7 +3934,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxMemberName { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsxMemberName { +impl IntoFormat for rome_js_syntax::JsxMemberName { type Format = FormatOwnedWithRule< rome_js_syntax::JsxMemberName, FormatNodeRule, @@ -3945,7 +3949,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxAttribute { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsxAttribute { +impl IntoFormat for rome_js_syntax::JsxAttribute { type Format = FormatOwnedWithRule< rome_js_syntax::JsxAttribute, FormatNodeRule, @@ -3960,7 +3964,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxSpreadAttribute { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsxSpreadAttribute { +impl IntoFormat for rome_js_syntax::JsxSpreadAttribute { type Format = FormatOwnedWithRule< rome_js_syntax::JsxSpreadAttribute, FormatNodeRule, @@ -3975,7 +3979,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxAttributeInitializerClause { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsxAttributeInitializerClause { +impl IntoFormat for rome_js_syntax::JsxAttributeInitializerClause { type Format = FormatOwnedWithRule< rome_js_syntax::JsxAttributeInitializerClause, FormatNodeRule, @@ -3987,7 +3991,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxString { FormatRefWithRule<'a, rome_js_syntax::JsxString, FormatNodeRule>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsxString { +impl IntoFormat for rome_js_syntax::JsxString { type Format = FormatOwnedWithRule>; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -4000,7 +4004,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxExpressionAttributeValue { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsxExpressionAttributeValue { +impl IntoFormat for rome_js_syntax::JsxExpressionAttributeValue { type Format = FormatOwnedWithRule< rome_js_syntax::JsxExpressionAttributeValue, FormatNodeRule, @@ -4012,7 +4016,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxText { FormatRefWithRule<'a, rome_js_syntax::JsxText, FormatNodeRule>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsxText { +impl IntoFormat for rome_js_syntax::JsxText { type Format = FormatOwnedWithRule>; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -4025,7 +4029,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxExpressionChild { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsxExpressionChild { +impl IntoFormat for rome_js_syntax::JsxExpressionChild { type Format = FormatOwnedWithRule< rome_js_syntax::JsxExpressionChild, FormatNodeRule, @@ -4040,7 +4044,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxSpreadChild { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsxSpreadChild { +impl IntoFormat for rome_js_syntax::JsxSpreadChild { type Format = FormatOwnedWithRule< rome_js_syntax::JsxSpreadChild, FormatNodeRule, @@ -4056,7 +4060,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsArrayAssignmentPatternElementList { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsArrayAssignmentPatternElementList { +impl IntoFormat for rome_js_syntax::JsArrayAssignmentPatternElementList { type Format = FormatOwnedWithRule< rome_js_syntax::JsArrayAssignmentPatternElementList, FormatJsArrayAssignmentPatternElementList, @@ -4072,7 +4076,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsArrayBindingPatternElementList { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsArrayBindingPatternElementList { +impl IntoFormat for rome_js_syntax::JsArrayBindingPatternElementList { type Format = FormatOwnedWithRule< rome_js_syntax::JsArrayBindingPatternElementList, FormatJsArrayBindingPatternElementList, @@ -4085,7 +4089,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsArrayElementList { FormatRefWithRule<'a, rome_js_syntax::JsArrayElementList, FormatJsArrayElementList>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsArrayElementList { +impl IntoFormat for rome_js_syntax::JsArrayElementList { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -4095,7 +4099,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsCallArgumentList { FormatRefWithRule<'a, rome_js_syntax::JsCallArgumentList, FormatJsCallArgumentList>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsCallArgumentList { +impl IntoFormat for rome_js_syntax::JsCallArgumentList { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -4104,7 +4108,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsClassMemberList { type Format = FormatRefWithRule<'a, rome_js_syntax::JsClassMemberList, FormatJsClassMemberList>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsClassMemberList { +impl IntoFormat for rome_js_syntax::JsClassMemberList { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -4117,7 +4121,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsConstructorModifierList { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsConstructorModifierList { +impl IntoFormat for rome_js_syntax::JsConstructorModifierList { type Format = FormatOwnedWithRule< rome_js_syntax::JsConstructorModifierList, FormatJsConstructorModifierList, @@ -4133,7 +4137,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsConstructorParameterList { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsConstructorParameterList { +impl IntoFormat for rome_js_syntax::JsConstructorParameterList { type Format = FormatOwnedWithRule< rome_js_syntax::JsConstructorParameterList, FormatJsConstructorParameterList, @@ -4145,7 +4149,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsDirectiveList { type Format = FormatRefWithRule<'a, rome_js_syntax::JsDirectiveList, FormatJsDirectiveList>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsDirectiveList { +impl IntoFormat for rome_js_syntax::JsDirectiveList { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -4158,7 +4162,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsExportNamedFromSpecifierList { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsExportNamedFromSpecifierList { +impl IntoFormat for rome_js_syntax::JsExportNamedFromSpecifierList { type Format = FormatOwnedWithRule< rome_js_syntax::JsExportNamedFromSpecifierList, FormatJsExportNamedFromSpecifierList, @@ -4174,7 +4178,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsExportNamedSpecifierList { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsExportNamedSpecifierList { +impl IntoFormat for rome_js_syntax::JsExportNamedSpecifierList { type Format = FormatOwnedWithRule< rome_js_syntax::JsExportNamedSpecifierList, FormatJsExportNamedSpecifierList, @@ -4190,7 +4194,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsImportAssertionEntryList { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsImportAssertionEntryList { +impl IntoFormat for rome_js_syntax::JsImportAssertionEntryList { type Format = FormatOwnedWithRule< rome_js_syntax::JsImportAssertionEntryList, FormatJsImportAssertionEntryList, @@ -4203,7 +4207,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsMethodModifierList { FormatRefWithRule<'a, rome_js_syntax::JsMethodModifierList, FormatJsMethodModifierList>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsMethodModifierList { +impl IntoFormat for rome_js_syntax::JsMethodModifierList { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -4213,7 +4217,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsModuleItemList { type Format = FormatRefWithRule<'a, rome_js_syntax::JsModuleItemList, FormatJsModuleItemList>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsModuleItemList { +impl IntoFormat for rome_js_syntax::JsModuleItemList { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -4226,7 +4230,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsNamedImportSpecifierList { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsNamedImportSpecifierList { +impl IntoFormat for rome_js_syntax::JsNamedImportSpecifierList { type Format = FormatOwnedWithRule< rome_js_syntax::JsNamedImportSpecifierList, FormatJsNamedImportSpecifierList, @@ -4242,7 +4246,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectAssignmentPatternPropertyList >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsObjectAssignmentPatternPropertyList { +impl IntoFormat for rome_js_syntax::JsObjectAssignmentPatternPropertyList { type Format = FormatOwnedWithRule< rome_js_syntax::JsObjectAssignmentPatternPropertyList, FormatJsObjectAssignmentPatternPropertyList, @@ -4258,7 +4262,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectBindingPatternPropertyList { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsObjectBindingPatternPropertyList { +impl IntoFormat for rome_js_syntax::JsObjectBindingPatternPropertyList { type Format = FormatOwnedWithRule< rome_js_syntax::JsObjectBindingPatternPropertyList, FormatJsObjectBindingPatternPropertyList, @@ -4271,7 +4275,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsObjectMemberList { FormatRefWithRule<'a, rome_js_syntax::JsObjectMemberList, FormatJsObjectMemberList>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsObjectMemberList { +impl IntoFormat for rome_js_syntax::JsObjectMemberList { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -4280,7 +4284,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsParameterList { type Format = FormatRefWithRule<'a, rome_js_syntax::JsParameterList, FormatJsParameterList>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsParameterList { +impl IntoFormat for rome_js_syntax::JsParameterList { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -4290,7 +4294,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsPropertyModifierList { FormatRefWithRule<'a, rome_js_syntax::JsPropertyModifierList, FormatJsPropertyModifierList>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsPropertyModifierList { +impl IntoFormat for rome_js_syntax::JsPropertyModifierList { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -4300,7 +4304,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsStatementList { type Format = FormatRefWithRule<'a, rome_js_syntax::JsStatementList, FormatJsStatementList>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsStatementList { +impl IntoFormat for rome_js_syntax::JsStatementList { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -4309,7 +4313,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsSwitchCaseList { type Format = FormatRefWithRule<'a, rome_js_syntax::JsSwitchCaseList, FormatJsSwitchCaseList>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsSwitchCaseList { +impl IntoFormat for rome_js_syntax::JsSwitchCaseList { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -4319,7 +4323,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsTemplateElementList { FormatRefWithRule<'a, rome_js_syntax::JsTemplateElementList, FormatJsTemplateElementList>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsTemplateElementList { +impl IntoFormat for rome_js_syntax::JsTemplateElementList { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -4333,7 +4337,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsVariableDeclaratorList { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsVariableDeclaratorList { +impl IntoFormat for rome_js_syntax::JsVariableDeclaratorList { type Format = FormatOwnedWithRule< rome_js_syntax::JsVariableDeclaratorList, FormatJsVariableDeclaratorList, @@ -4345,7 +4349,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxAttributeList { type Format = FormatRefWithRule<'a, rome_js_syntax::JsxAttributeList, FormatJsxAttributeList>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsxAttributeList { +impl IntoFormat for rome_js_syntax::JsxAttributeList { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -4354,7 +4358,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxChildList { type Format = FormatRefWithRule<'a, rome_js_syntax::JsxChildList, FormatJsxChildList>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsxChildList { +impl IntoFormat for rome_js_syntax::JsxChildList { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -4363,7 +4367,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsEnumMemberList { type Format = FormatRefWithRule<'a, rome_js_syntax::TsEnumMemberList, FormatTsEnumMemberList>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsEnumMemberList { +impl IntoFormat for rome_js_syntax::TsEnumMemberList { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -4376,7 +4380,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsIndexSignatureModifierList { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsIndexSignatureModifierList { +impl IntoFormat for rome_js_syntax::TsIndexSignatureModifierList { type Format = FormatOwnedWithRule< rome_js_syntax::TsIndexSignatureModifierList, FormatTsIndexSignatureModifierList, @@ -4392,7 +4396,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsIntersectionTypeElementList { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsIntersectionTypeElementList { +impl IntoFormat for rome_js_syntax::TsIntersectionTypeElementList { type Format = FormatOwnedWithRule< rome_js_syntax::TsIntersectionTypeElementList, FormatTsIntersectionTypeElementList, @@ -4408,7 +4412,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsMethodSignatureModifierList { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsMethodSignatureModifierList { +impl IntoFormat for rome_js_syntax::TsMethodSignatureModifierList { type Format = FormatOwnedWithRule< rome_js_syntax::TsMethodSignatureModifierList, FormatTsMethodSignatureModifierList, @@ -4424,7 +4428,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsPropertyParameterModifierList { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsPropertyParameterModifierList { +impl IntoFormat for rome_js_syntax::TsPropertyParameterModifierList { type Format = FormatOwnedWithRule< rome_js_syntax::TsPropertyParameterModifierList, FormatTsPropertyParameterModifierList, @@ -4440,7 +4444,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsPropertySignatureModifierList { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsPropertySignatureModifierList { +impl IntoFormat for rome_js_syntax::TsPropertySignatureModifierList { type Format = FormatOwnedWithRule< rome_js_syntax::TsPropertySignatureModifierList, FormatTsPropertySignatureModifierList, @@ -4453,7 +4457,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTemplateElementList { FormatRefWithRule<'a, rome_js_syntax::TsTemplateElementList, FormatTsTemplateElementList>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsTemplateElementList { +impl IntoFormat for rome_js_syntax::TsTemplateElementList { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -4464,7 +4468,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTupleTypeElementList { FormatRefWithRule<'a, rome_js_syntax::TsTupleTypeElementList, FormatTsTupleTypeElementList>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsTupleTypeElementList { +impl IntoFormat for rome_js_syntax::TsTupleTypeElementList { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -4475,7 +4479,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeArgumentList { FormatRefWithRule<'a, rome_js_syntax::TsTypeArgumentList, FormatTsTypeArgumentList>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsTypeArgumentList { +impl IntoFormat for rome_js_syntax::TsTypeArgumentList { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -4484,7 +4488,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeList { type Format = FormatRefWithRule<'a, rome_js_syntax::TsTypeList, FormatTsTypeList>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsTypeList { +impl IntoFormat for rome_js_syntax::TsTypeList { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -4493,7 +4497,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeMemberList { type Format = FormatRefWithRule<'a, rome_js_syntax::TsTypeMemberList, FormatTsTypeMemberList>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsTypeMemberList { +impl IntoFormat for rome_js_syntax::TsTypeMemberList { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -4503,7 +4507,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsTypeParameterList { FormatRefWithRule<'a, rome_js_syntax::TsTypeParameterList, FormatTsTypeParameterList>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsTypeParameterList { +impl IntoFormat for rome_js_syntax::TsTypeParameterList { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -4514,7 +4518,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsUnionTypeVariantList { FormatRefWithRule<'a, rome_js_syntax::TsUnionTypeVariantList, FormatTsUnionTypeVariantList>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsUnionTypeVariantList { +impl IntoFormat for rome_js_syntax::TsUnionTypeVariantList { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -4524,7 +4528,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsUnknown { FormatRefWithRule<'a, rome_js_syntax::JsUnknown, FormatNodeRule>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsUnknown { +impl IntoFormat for rome_js_syntax::JsUnknown { type Format = FormatOwnedWithRule>; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -4537,7 +4541,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsUnknownStatement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsUnknownStatement { +impl IntoFormat for rome_js_syntax::JsUnknownStatement { type Format = FormatOwnedWithRule< rome_js_syntax::JsUnknownStatement, FormatNodeRule, @@ -4552,7 +4556,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsUnknownExpression { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsUnknownExpression { +impl IntoFormat for rome_js_syntax::JsUnknownExpression { type Format = FormatOwnedWithRule< rome_js_syntax::JsUnknownExpression, FormatNodeRule, @@ -4567,7 +4571,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsUnknownMember { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsUnknownMember { +impl IntoFormat for rome_js_syntax::JsUnknownMember { type Format = FormatOwnedWithRule< rome_js_syntax::JsUnknownMember, FormatNodeRule, @@ -4582,7 +4586,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsUnknownBinding { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsUnknownBinding { +impl IntoFormat for rome_js_syntax::JsUnknownBinding { type Format = FormatOwnedWithRule< rome_js_syntax::JsUnknownBinding, FormatNodeRule, @@ -4597,7 +4601,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsUnknownAssignment { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsUnknownAssignment { +impl IntoFormat for rome_js_syntax::JsUnknownAssignment { type Format = FormatOwnedWithRule< rome_js_syntax::JsUnknownAssignment, FormatNodeRule, @@ -4612,7 +4616,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsUnknownParameter { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsUnknownParameter { +impl IntoFormat for rome_js_syntax::JsUnknownParameter { type Format = FormatOwnedWithRule< rome_js_syntax::JsUnknownParameter, FormatNodeRule, @@ -4627,7 +4631,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsUnknownImportAssertionEntry { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsUnknownImportAssertionEntry { +impl IntoFormat for rome_js_syntax::JsUnknownImportAssertionEntry { type Format = FormatOwnedWithRule< rome_js_syntax::JsUnknownImportAssertionEntry, FormatNodeRule, @@ -4642,7 +4646,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsUnknownNamedImportSpecifier { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsUnknownNamedImportSpecifier { +impl IntoFormat for rome_js_syntax::JsUnknownNamedImportSpecifier { type Format = FormatOwnedWithRule< rome_js_syntax::JsUnknownNamedImportSpecifier, FormatNodeRule, @@ -4654,7 +4658,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyRoot { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyRoot, FormatJsAnyRoot>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyRoot { +impl IntoFormat for rome_js_syntax::JsAnyRoot { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -4663,7 +4667,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyExpression { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyExpression, FormatJsAnyExpression>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyExpression { +impl IntoFormat for rome_js_syntax::JsAnyExpression { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -4672,7 +4676,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyStatement { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyStatement, FormatJsAnyStatement>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyStatement { +impl IntoFormat for rome_js_syntax::JsAnyStatement { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -4682,7 +4686,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyForInitializer { FormatRefWithRule<'a, rome_js_syntax::JsAnyForInitializer, FormatJsAnyForInitializer>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyForInitializer { +impl IntoFormat for rome_js_syntax::JsAnyForInitializer { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -4696,7 +4700,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyForInOrOfInitializer { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyForInOrOfInitializer { +impl IntoFormat for rome_js_syntax::JsAnyForInOrOfInitializer { type Format = FormatOwnedWithRule< rome_js_syntax::JsAnyForInOrOfInitializer, FormatJsAnyForInOrOfInitializer, @@ -4709,7 +4713,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyAssignmentPattern { FormatRefWithRule<'a, rome_js_syntax::JsAnyAssignmentPattern, FormatJsAnyAssignmentPattern>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyAssignmentPattern { +impl IntoFormat for rome_js_syntax::JsAnyAssignmentPattern { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -4719,7 +4723,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnySwitchClause { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnySwitchClause, FormatJsAnySwitchClause>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnySwitchClause { +impl IntoFormat for rome_js_syntax::JsAnySwitchClause { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -4729,7 +4733,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyBindingPattern { FormatRefWithRule<'a, rome_js_syntax::JsAnyBindingPattern, FormatJsAnyBindingPattern>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyBindingPattern { +impl IntoFormat for rome_js_syntax::JsAnyBindingPattern { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -4740,7 +4744,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyDeclarationClause { FormatRefWithRule<'a, rome_js_syntax::JsAnyDeclarationClause, FormatJsAnyDeclarationClause>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyDeclarationClause { +impl IntoFormat for rome_js_syntax::JsAnyDeclarationClause { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -4751,7 +4755,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyLiteralExpression { FormatRefWithRule<'a, rome_js_syntax::JsAnyLiteralExpression, FormatJsAnyLiteralExpression>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyLiteralExpression { +impl IntoFormat for rome_js_syntax::JsAnyLiteralExpression { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -4762,7 +4766,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyTemplateElement { FormatRefWithRule<'a, rome_js_syntax::JsAnyTemplateElement, FormatJsAnyTemplateElement>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyTemplateElement { +impl IntoFormat for rome_js_syntax::JsAnyTemplateElement { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -4772,7 +4776,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyBinding { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyBinding, FormatJsAnyBinding>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyBinding { +impl IntoFormat for rome_js_syntax::JsAnyBinding { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -4785,7 +4789,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyArrowFunctionParameters { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyArrowFunctionParameters { +impl IntoFormat for rome_js_syntax::JsAnyArrowFunctionParameters { type Format = FormatOwnedWithRule< rome_js_syntax::JsAnyArrowFunctionParameters, FormatJsAnyArrowFunctionParameters, @@ -4797,7 +4801,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyFunctionBody { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyFunctionBody, FormatJsAnyFunctionBody>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyFunctionBody { +impl IntoFormat for rome_js_syntax::JsAnyFunctionBody { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -4806,7 +4810,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyArrayElement { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyArrayElement, FormatJsAnyArrayElement>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyArrayElement { +impl IntoFormat for rome_js_syntax::JsAnyArrayElement { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -4815,7 +4819,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyName { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyName, FormatJsAnyName>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyName { +impl IntoFormat for rome_js_syntax::JsAnyName { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -4824,7 +4828,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyInProperty { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyInProperty, FormatJsAnyInProperty>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyInProperty { +impl IntoFormat for rome_js_syntax::JsAnyInProperty { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -4833,7 +4837,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyAssignment { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyAssignment, FormatJsAnyAssignment>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyAssignment { +impl IntoFormat for rome_js_syntax::JsAnyAssignment { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -4843,7 +4847,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyObjectMemberName { FormatRefWithRule<'a, rome_js_syntax::JsAnyObjectMemberName, FormatJsAnyObjectMemberName>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyObjectMemberName { +impl IntoFormat for rome_js_syntax::JsAnyObjectMemberName { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -4853,7 +4857,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyObjectMember { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyObjectMember, FormatJsAnyObjectMember>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyObjectMember { +impl IntoFormat for rome_js_syntax::JsAnyObjectMember { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -4863,7 +4867,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyFormalParameter { FormatRefWithRule<'a, rome_js_syntax::JsAnyFormalParameter, FormatJsAnyFormalParameter>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyFormalParameter { +impl IntoFormat for rome_js_syntax::JsAnyFormalParameter { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -4873,7 +4877,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyClassMember { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyClassMember, FormatJsAnyClassMember>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyClassMember { +impl IntoFormat for rome_js_syntax::JsAnyClassMember { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -4882,7 +4886,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyClass { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyClass, FormatJsAnyClass>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyClass { +impl IntoFormat for rome_js_syntax::JsAnyClass { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -4892,7 +4896,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyClassMemberName { FormatRefWithRule<'a, rome_js_syntax::JsAnyClassMemberName, FormatJsAnyClassMemberName>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyClassMemberName { +impl IntoFormat for rome_js_syntax::JsAnyClassMemberName { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -4906,7 +4910,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyConstructorParameter { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyConstructorParameter { +impl IntoFormat for rome_js_syntax::JsAnyConstructorParameter { type Format = FormatOwnedWithRule< rome_js_syntax::JsAnyConstructorParameter, FormatJsAnyConstructorParameter, @@ -4922,7 +4926,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyPropertyParameterModifier { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsAnyPropertyParameterModifier { +impl IntoFormat for rome_js_syntax::TsAnyPropertyParameterModifier { type Format = FormatOwnedWithRule< rome_js_syntax::TsAnyPropertyParameterModifier, FormatTsAnyPropertyParameterModifier, @@ -4938,7 +4942,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyPropertyAnnotation { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsAnyPropertyAnnotation { +impl IntoFormat for rome_js_syntax::TsAnyPropertyAnnotation { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -4949,7 +4953,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyPropertyModifier { FormatRefWithRule<'a, rome_js_syntax::JsAnyPropertyModifier, FormatJsAnyPropertyModifier>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyPropertyModifier { +impl IntoFormat for rome_js_syntax::JsAnyPropertyModifier { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -4963,7 +4967,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyPropertySignatureAnnotation { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsAnyPropertySignatureAnnotation { +impl IntoFormat for rome_js_syntax::TsAnyPropertySignatureAnnotation { type Format = FormatOwnedWithRule< rome_js_syntax::TsAnyPropertySignatureAnnotation, FormatTsAnyPropertySignatureAnnotation, @@ -4979,7 +4983,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyPropertySignatureModifier { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsAnyPropertySignatureModifier { +impl IntoFormat for rome_js_syntax::TsAnyPropertySignatureModifier { type Format = FormatOwnedWithRule< rome_js_syntax::TsAnyPropertySignatureModifier, FormatTsAnyPropertySignatureModifier, @@ -4992,7 +4996,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyMethodModifier { FormatRefWithRule<'a, rome_js_syntax::JsAnyMethodModifier, FormatJsAnyMethodModifier>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyMethodModifier { +impl IntoFormat for rome_js_syntax::JsAnyMethodModifier { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -5006,7 +5010,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyMethodSignatureModifier { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsAnyMethodSignatureModifier { +impl IntoFormat for rome_js_syntax::TsAnyMethodSignatureModifier { type Format = FormatOwnedWithRule< rome_js_syntax::TsAnyMethodSignatureModifier, FormatTsAnyMethodSignatureModifier, @@ -5022,7 +5026,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyIndexSignatureModifier { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsAnyIndexSignatureModifier { +impl IntoFormat for rome_js_syntax::TsAnyIndexSignatureModifier { type Format = FormatOwnedWithRule< rome_js_syntax::TsAnyIndexSignatureModifier, FormatTsAnyIndexSignatureModifier, @@ -5034,7 +5038,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsType { type Format = FormatRefWithRule<'a, rome_js_syntax::TsType, FormatTsType>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsType { +impl IntoFormat for rome_js_syntax::TsType { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -5047,7 +5051,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyArrayAssignmentPatternElement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyArrayAssignmentPatternElement { +impl IntoFormat for rome_js_syntax::JsAnyArrayAssignmentPatternElement { type Format = FormatOwnedWithRule< rome_js_syntax::JsAnyArrayAssignmentPatternElement, FormatJsAnyArrayAssignmentPatternElement, @@ -5063,7 +5067,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyObjectAssignmentPatternMember { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyObjectAssignmentPatternMember { +impl IntoFormat for rome_js_syntax::JsAnyObjectAssignmentPatternMember { type Format = FormatOwnedWithRule< rome_js_syntax::JsAnyObjectAssignmentPatternMember, FormatJsAnyObjectAssignmentPatternMember, @@ -5079,7 +5083,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyArrayBindingPatternElement { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyArrayBindingPatternElement { +impl IntoFormat for rome_js_syntax::JsAnyArrayBindingPatternElement { type Format = FormatOwnedWithRule< rome_js_syntax::JsAnyArrayBindingPatternElement, FormatJsAnyArrayBindingPatternElement, @@ -5095,7 +5099,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyObjectBindingPatternMember { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyObjectBindingPatternMember { +impl IntoFormat for rome_js_syntax::JsAnyObjectBindingPatternMember { type Format = FormatOwnedWithRule< rome_js_syntax::JsAnyObjectBindingPatternMember, FormatJsAnyObjectBindingPatternMember, @@ -5107,7 +5111,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyDeclaration { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyDeclaration, FormatJsAnyDeclaration>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyDeclaration { +impl IntoFormat for rome_js_syntax::JsAnyDeclaration { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -5116,7 +5120,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyReturnType { type Format = FormatRefWithRule<'a, rome_js_syntax::TsAnyReturnType, FormatTsAnyReturnType>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsAnyReturnType { +impl IntoFormat for rome_js_syntax::TsAnyReturnType { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -5129,7 +5133,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyVariableAnnotation { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsAnyVariableAnnotation { +impl IntoFormat for rome_js_syntax::TsAnyVariableAnnotation { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -5139,7 +5143,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyModuleItem { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyModuleItem, FormatJsAnyModuleItem>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyModuleItem { +impl IntoFormat for rome_js_syntax::JsAnyModuleItem { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -5148,7 +5152,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyImportClause { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyImportClause, FormatJsAnyImportClause>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyImportClause { +impl IntoFormat for rome_js_syntax::JsAnyImportClause { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -5157,7 +5161,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyNamedImport { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyNamedImport, FormatJsAnyNamedImport>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyNamedImport { +impl IntoFormat for rome_js_syntax::JsAnyNamedImport { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -5170,7 +5174,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyNamedImportSpecifier { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyNamedImportSpecifier { +impl IntoFormat for rome_js_syntax::JsAnyNamedImportSpecifier { type Format = FormatOwnedWithRule< rome_js_syntax::JsAnyNamedImportSpecifier, FormatJsAnyNamedImportSpecifier, @@ -5186,7 +5190,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyImportAssertionEntry { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyImportAssertionEntry { +impl IntoFormat for rome_js_syntax::JsAnyImportAssertionEntry { type Format = FormatOwnedWithRule< rome_js_syntax::JsAnyImportAssertionEntry, FormatJsAnyImportAssertionEntry, @@ -5198,7 +5202,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyExportClause { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyExportClause, FormatJsAnyExportClause>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyExportClause { +impl IntoFormat for rome_js_syntax::JsAnyExportClause { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -5211,7 +5215,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyExportDefaultDeclaration { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyExportDefaultDeclaration { +impl IntoFormat for rome_js_syntax::JsAnyExportDefaultDeclaration { type Format = FormatOwnedWithRule< rome_js_syntax::JsAnyExportDefaultDeclaration, FormatJsAnyExportDefaultDeclaration, @@ -5227,7 +5231,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyExportNamedSpecifier { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyExportNamedSpecifier { +impl IntoFormat for rome_js_syntax::JsAnyExportNamedSpecifier { type Format = FormatOwnedWithRule< rome_js_syntax::JsAnyExportNamedSpecifier, FormatJsAnyExportNamedSpecifier, @@ -5239,7 +5243,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyFunction { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyFunction, FormatJsAnyFunction>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyFunction { +impl IntoFormat for rome_js_syntax::JsAnyFunction { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -5248,7 +5252,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyParameter { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyParameter, FormatJsAnyParameter>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyParameter { +impl IntoFormat for rome_js_syntax::JsAnyParameter { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -5257,7 +5261,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsAnyCallArgument { type Format = FormatRefWithRule<'a, rome_js_syntax::JsAnyCallArgument, FormatJsAnyCallArgument>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsAnyCallArgument { +impl IntoFormat for rome_js_syntax::JsAnyCallArgument { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -5266,7 +5270,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyName { type Format = FormatRefWithRule<'a, rome_js_syntax::TsAnyName, FormatTsAnyName>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsAnyName { +impl IntoFormat for rome_js_syntax::TsAnyName { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -5276,7 +5280,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyModuleReference { FormatRefWithRule<'a, rome_js_syntax::TsAnyModuleReference, FormatTsAnyModuleReference>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsAnyModuleReference { +impl IntoFormat for rome_js_syntax::TsAnyModuleReference { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -5286,7 +5290,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyModuleName { type Format = FormatRefWithRule<'a, rome_js_syntax::TsAnyModuleName, FormatTsAnyModuleName>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsAnyModuleName { +impl IntoFormat for rome_js_syntax::TsAnyModuleName { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -5299,7 +5303,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyExternalModuleDeclarationBody { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsAnyExternalModuleDeclarationBody { +impl IntoFormat for rome_js_syntax::TsAnyExternalModuleDeclarationBody { type Format = FormatOwnedWithRule< rome_js_syntax::TsAnyExternalModuleDeclarationBody, FormatTsAnyExternalModuleDeclarationBody, @@ -5315,7 +5319,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyTypePredicateParameterName { >; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsAnyTypePredicateParameterName { +impl IntoFormat for rome_js_syntax::TsAnyTypePredicateParameterName { type Format = FormatOwnedWithRule< rome_js_syntax::TsAnyTypePredicateParameterName, FormatTsAnyTypePredicateParameterName, @@ -5327,7 +5331,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyTypeMember { type Format = FormatRefWithRule<'a, rome_js_syntax::TsAnyTypeMember, FormatTsAnyTypeMember>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsAnyTypeMember { +impl IntoFormat for rome_js_syntax::TsAnyTypeMember { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -5337,7 +5341,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyTupleTypeElement { FormatRefWithRule<'a, rome_js_syntax::TsAnyTupleTypeElement, FormatTsAnyTupleTypeElement>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsAnyTupleTypeElement { +impl IntoFormat for rome_js_syntax::TsAnyTupleTypeElement { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -5348,7 +5352,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::TsAnyTemplateElement { FormatRefWithRule<'a, rome_js_syntax::TsAnyTemplateElement, FormatTsAnyTemplateElement>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::TsAnyTemplateElement { +impl IntoFormat for rome_js_syntax::TsAnyTemplateElement { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -5358,7 +5362,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxAnyTag { type Format = FormatRefWithRule<'a, rome_js_syntax::JsxAnyTag, FormatJsxAnyTag>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsxAnyTag { +impl IntoFormat for rome_js_syntax::JsxAnyTag { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -5367,7 +5371,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxAnyElementName { type Format = FormatRefWithRule<'a, rome_js_syntax::JsxAnyElementName, FormatJsxAnyElementName>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsxAnyElementName { +impl IntoFormat for rome_js_syntax::JsxAnyElementName { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -5376,7 +5380,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxAnyObjectName { type Format = FormatRefWithRule<'a, rome_js_syntax::JsxAnyObjectName, FormatJsxAnyObjectName>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsxAnyObjectName { +impl IntoFormat for rome_js_syntax::JsxAnyObjectName { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -5385,7 +5389,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxAnyName { type Format = FormatRefWithRule<'a, rome_js_syntax::JsxAnyName, FormatJsxAnyName>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsxAnyName { +impl IntoFormat for rome_js_syntax::JsxAnyName { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -5394,7 +5398,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxAnyAttribute { type Format = FormatRefWithRule<'a, rome_js_syntax::JsxAnyAttribute, FormatJsxAnyAttribute>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsxAnyAttribute { +impl IntoFormat for rome_js_syntax::JsxAnyAttribute { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } @@ -5404,7 +5408,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxAnyAttributeName { FormatRefWithRule<'a, rome_js_syntax::JsxAnyAttributeName, FormatJsxAnyAttributeName>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsxAnyAttributeName { +impl IntoFormat for rome_js_syntax::JsxAnyAttributeName { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -5415,7 +5419,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxAnyAttributeValue { FormatRefWithRule<'a, rome_js_syntax::JsxAnyAttributeValue, FormatJsxAnyAttributeValue>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsxAnyAttributeValue { +impl IntoFormat for rome_js_syntax::JsxAnyAttributeValue { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } @@ -5425,7 +5429,7 @@ impl<'a> AsFormat<'a> for rome_js_syntax::JsxAnyChild { type Format = FormatRefWithRule<'a, rome_js_syntax::JsxAnyChild, FormatJsxAnyChild>; fn format(&'a self) -> Self::Format { FormatRefWithRule::new(self) } } -impl IntoFormat for rome_js_syntax::JsxAnyChild { +impl IntoFormat for rome_js_syntax::JsxAnyChild { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self) } } diff --git a/crates/rome_js_formatter/src/js/any/array_assignment_pattern_element.rs b/crates/rome_js_formatter/src/js/any/array_assignment_pattern_element.rs index b7c4d7cd8e2..d5eed91c0d8 100644 --- a/crates/rome_js_formatter/src/js/any/array_assignment_pattern_element.rs +++ b/crates/rome_js_formatter/src/js/any/array_assignment_pattern_element.rs @@ -5,23 +5,18 @@ use crate::prelude::*; use rome_js_syntax::JsAnyArrayAssignmentPatternElement; impl FormatRule for FormatJsAnyArrayAssignmentPatternElement { type Context = JsFormatContext; - fn format( - node: &JsAnyArrayAssignmentPatternElement, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt(node: &JsAnyArrayAssignmentPatternElement, f: &mut JsFormatter) -> FormatResult<()> { match node { JsAnyArrayAssignmentPatternElement::JsAssignmentWithDefault(node) => { - formatted![formatter, [node.format()]] + node.format().fmt(f) } JsAnyArrayAssignmentPatternElement::JsAnyAssignmentPattern(node) => { - formatted![formatter, [node.format()]] + node.format().fmt(f) } JsAnyArrayAssignmentPatternElement::JsArrayAssignmentPatternRestElement(node) => { - formatted![formatter, [node.format()]] - } - JsAnyArrayAssignmentPatternElement::JsArrayHole(node) => { - formatted![formatter, [node.format()]] + node.format().fmt(f) } + JsAnyArrayAssignmentPatternElement::JsArrayHole(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/array_binding_pattern_element.rs b/crates/rome_js_formatter/src/js/any/array_binding_pattern_element.rs index 44c15e78ef0..f81920be54a 100644 --- a/crates/rome_js_formatter/src/js/any/array_binding_pattern_element.rs +++ b/crates/rome_js_formatter/src/js/any/array_binding_pattern_element.rs @@ -5,22 +5,15 @@ use crate::prelude::*; use rome_js_syntax::JsAnyArrayBindingPatternElement; impl FormatRule for FormatJsAnyArrayBindingPatternElement { type Context = JsFormatContext; - fn format( - node: &JsAnyArrayBindingPatternElement, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt(node: &JsAnyArrayBindingPatternElement, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyArrayBindingPatternElement::JsArrayHole(node) => { - formatted![formatter, [node.format()]] - } - JsAnyArrayBindingPatternElement::JsAnyBindingPattern(node) => { - formatted![formatter, [node.format()]] - } + JsAnyArrayBindingPatternElement::JsArrayHole(node) => node.format().fmt(f), + JsAnyArrayBindingPatternElement::JsAnyBindingPattern(node) => node.format().fmt(f), JsAnyArrayBindingPatternElement::JsBindingPatternWithDefault(node) => { - formatted![formatter, [node.format()]] + node.format().fmt(f) } JsAnyArrayBindingPatternElement::JsArrayBindingPatternRestElement(node) => { - formatted![formatter, [node.format()]] + node.format().fmt(f) } } } diff --git a/crates/rome_js_formatter/src/js/any/array_element.rs b/crates/rome_js_formatter/src/js/any/array_element.rs index f5b1fe58566..4a88be83639 100644 --- a/crates/rome_js_formatter/src/js/any/array_element.rs +++ b/crates/rome_js_formatter/src/js/any/array_element.rs @@ -5,11 +5,11 @@ use crate::prelude::*; use rome_js_syntax::JsAnyArrayElement; impl FormatRule for FormatJsAnyArrayElement { type Context = JsFormatContext; - fn format(node: &JsAnyArrayElement, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsAnyArrayElement, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyArrayElement::JsAnyExpression(node) => formatted![formatter, [node.format()]], - JsAnyArrayElement::JsSpread(node) => formatted![formatter, [node.format()]], - JsAnyArrayElement::JsArrayHole(node) => formatted![formatter, [node.format()]], + JsAnyArrayElement::JsAnyExpression(node) => node.format().fmt(f), + JsAnyArrayElement::JsSpread(node) => node.format().fmt(f), + JsAnyArrayElement::JsArrayHole(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/arrow_function_parameters.rs b/crates/rome_js_formatter/src/js/any/arrow_function_parameters.rs index acf11162fe0..7cd5b210610 100644 --- a/crates/rome_js_formatter/src/js/any/arrow_function_parameters.rs +++ b/crates/rome_js_formatter/src/js/any/arrow_function_parameters.rs @@ -5,17 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsAnyArrowFunctionParameters; impl FormatRule for FormatJsAnyArrowFunctionParameters { type Context = JsFormatContext; - fn format( - node: &JsAnyArrowFunctionParameters, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt(node: &JsAnyArrowFunctionParameters, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyArrowFunctionParameters::JsParameters(node) => { - formatted![formatter, [node.format()]] - } - JsAnyArrowFunctionParameters::JsAnyBinding(node) => { - formatted![formatter, [node.format()]] - } + JsAnyArrowFunctionParameters::JsParameters(node) => node.format().fmt(f), + JsAnyArrowFunctionParameters::JsAnyBinding(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/assignment.rs b/crates/rome_js_formatter/src/js/any/assignment.rs index 56f08e3a433..f0f3f0af8f6 100644 --- a/crates/rome_js_formatter/src/js/any/assignment.rs +++ b/crates/rome_js_formatter/src/js/any/assignment.rs @@ -5,26 +5,16 @@ use crate::prelude::*; use rome_js_syntax::JsAnyAssignment; impl FormatRule for FormatJsAnyAssignment { type Context = JsFormatContext; - fn format(node: &JsAnyAssignment, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsAnyAssignment, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyAssignment::JsIdentifierAssignment(node) => formatted![formatter, [node.format()]], - JsAnyAssignment::JsStaticMemberAssignment(node) => { - formatted![formatter, [node.format()]] - } - JsAnyAssignment::JsComputedMemberAssignment(node) => { - formatted![formatter, [node.format()]] - } - JsAnyAssignment::JsParenthesizedAssignment(node) => { - formatted![formatter, [node.format()]] - } - JsAnyAssignment::TsNonNullAssertionAssignment(node) => { - formatted![formatter, [node.format()]] - } - JsAnyAssignment::TsAsAssignment(node) => formatted![formatter, [node.format()]], - JsAnyAssignment::TsTypeAssertionAssignment(node) => { - formatted![formatter, [node.format()]] - } - JsAnyAssignment::JsUnknownAssignment(node) => formatted![formatter, [node.format()]], + JsAnyAssignment::JsIdentifierAssignment(node) => node.format().fmt(f), + JsAnyAssignment::JsStaticMemberAssignment(node) => node.format().fmt(f), + JsAnyAssignment::JsComputedMemberAssignment(node) => node.format().fmt(f), + JsAnyAssignment::JsParenthesizedAssignment(node) => node.format().fmt(f), + JsAnyAssignment::TsNonNullAssertionAssignment(node) => node.format().fmt(f), + JsAnyAssignment::TsAsAssignment(node) => node.format().fmt(f), + JsAnyAssignment::TsTypeAssertionAssignment(node) => node.format().fmt(f), + JsAnyAssignment::JsUnknownAssignment(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/assignment_pattern.rs b/crates/rome_js_formatter/src/js/any/assignment_pattern.rs index a7316b0416e..4a980764431 100644 --- a/crates/rome_js_formatter/src/js/any/assignment_pattern.rs +++ b/crates/rome_js_formatter/src/js/any/assignment_pattern.rs @@ -5,18 +5,11 @@ use crate::prelude::*; use rome_js_syntax::JsAnyAssignmentPattern; impl FormatRule for FormatJsAnyAssignmentPattern { type Context = JsFormatContext; - fn format( - node: &JsAnyAssignmentPattern, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt(node: &JsAnyAssignmentPattern, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyAssignmentPattern::JsAnyAssignment(node) => formatted![formatter, [node.format()]], - JsAnyAssignmentPattern::JsArrayAssignmentPattern(node) => { - formatted![formatter, [node.format()]] - } - JsAnyAssignmentPattern::JsObjectAssignmentPattern(node) => { - formatted![formatter, [node.format()]] - } + JsAnyAssignmentPattern::JsAnyAssignment(node) => node.format().fmt(f), + JsAnyAssignmentPattern::JsArrayAssignmentPattern(node) => node.format().fmt(f), + JsAnyAssignmentPattern::JsObjectAssignmentPattern(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/binding.rs b/crates/rome_js_formatter/src/js/any/binding.rs index a7984ce9ea1..1bb654f3aa2 100644 --- a/crates/rome_js_formatter/src/js/any/binding.rs +++ b/crates/rome_js_formatter/src/js/any/binding.rs @@ -5,10 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsAnyBinding; impl FormatRule for FormatJsAnyBinding { type Context = JsFormatContext; - fn format(node: &JsAnyBinding, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsAnyBinding, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyBinding::JsIdentifierBinding(node) => formatted![formatter, [node.format()]], - JsAnyBinding::JsUnknownBinding(node) => formatted![formatter, [node.format()]], + JsAnyBinding::JsIdentifierBinding(node) => node.format().fmt(f), + JsAnyBinding::JsUnknownBinding(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/binding_pattern.rs b/crates/rome_js_formatter/src/js/any/binding_pattern.rs index 4cc9376a8e1..78053569648 100644 --- a/crates/rome_js_formatter/src/js/any/binding_pattern.rs +++ b/crates/rome_js_formatter/src/js/any/binding_pattern.rs @@ -5,15 +5,11 @@ use crate::prelude::*; use rome_js_syntax::JsAnyBindingPattern; impl FormatRule for FormatJsAnyBindingPattern { type Context = JsFormatContext; - fn format(node: &JsAnyBindingPattern, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsAnyBindingPattern, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyBindingPattern::JsAnyBinding(node) => formatted![formatter, [node.format()]], - JsAnyBindingPattern::JsArrayBindingPattern(node) => { - formatted![formatter, [node.format()]] - } - JsAnyBindingPattern::JsObjectBindingPattern(node) => { - formatted![formatter, [node.format()]] - } + JsAnyBindingPattern::JsAnyBinding(node) => node.format().fmt(f), + JsAnyBindingPattern::JsArrayBindingPattern(node) => node.format().fmt(f), + JsAnyBindingPattern::JsObjectBindingPattern(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/call_argument.rs b/crates/rome_js_formatter/src/js/any/call_argument.rs index 2e02881bb81..ee2bd215aff 100644 --- a/crates/rome_js_formatter/src/js/any/call_argument.rs +++ b/crates/rome_js_formatter/src/js/any/call_argument.rs @@ -5,10 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsAnyCallArgument; impl FormatRule for FormatJsAnyCallArgument { type Context = JsFormatContext; - fn format(node: &JsAnyCallArgument, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsAnyCallArgument, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyCallArgument::JsAnyExpression(node) => formatted![formatter, [node.format()]], - JsAnyCallArgument::JsSpread(node) => formatted![formatter, [node.format()]], + JsAnyCallArgument::JsAnyExpression(node) => node.format().fmt(f), + JsAnyCallArgument::JsSpread(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/class.rs b/crates/rome_js_formatter/src/js/any/class.rs index 212ee7c6c5e..9d0ee3e5fbb 100644 --- a/crates/rome_js_formatter/src/js/any/class.rs +++ b/crates/rome_js_formatter/src/js/any/class.rs @@ -1,52 +1,49 @@ use crate::generated::FormatJsAnyClass; +use rome_formatter::write; + +use crate::builders::format_delimited; use crate::prelude::*; use rome_js_syntax::JsAnyClass; -use rome_rowan::AstNode; impl FormatRule for FormatJsAnyClass { type Context = JsFormatContext; - fn format(node: &JsAnyClass, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsAnyClass, f: &mut JsFormatter) -> FormatResult<()> { let abstract_token = node.abstract_token(); let id = node.id(); let extends = node.extends_clause(); let implements_clause = node.implements_clause(); - let format = implements_clause.format(); + if let Some(abstract_token) = abstract_token { + write!(f, [abstract_token.format(), space_token()])?; + } + + write!(f, [node.class_token().format()])?; + + if let Some(id) = id? { + write!(f, [space_token(), id.format()])?; + } + + write!(f, [node.type_parameters().format()])?; + + if let Some(extends) = extends { + write!(f, [space_token(), extends.format()])?; + } - let implements_clause = format.with_or_empty(|implements_clause| { - formatted![formatter, [space_token(), implements_clause]] - }); + if let Some(implements_clause) = implements_clause { + write!(f, [space_token(), implements_clause.format()])?; + } - formatted![ - formatter, + write![ + f, [ - abstract_token - .format() - .with_or_empty(|token| formatted![formatter, [token, space_token()]]), - node.class_token().format(), - id.format() - .with_or_empty(|id| formatted![formatter, [space_token(), id]]), - node.type_parameters().format(), - extends.format().with_or_empty(|extends_clause| formatted![ - formatter, - [space_token(), extends_clause] - ]), - implements_clause, space_token(), - formatter - .delimited( - &node.l_curly_token()?, - join_elements_hard_line( - node.members() - .into_iter() - .map(|node| node.syntax().clone()) - .zip(formatter.format_all(node.members().iter().formatted())?) - ), - &node.r_curly_token()? - ) - .block_indent() - .finish() + format_delimited( + &node.l_curly_token()?, + &node.members().format(), + &node.r_curly_token()? + ) + .block_indent() ] ] } diff --git a/crates/rome_js_formatter/src/js/any/class_member.rs b/crates/rome_js_formatter/src/js/any/class_member.rs index 96991ef3156..f5aa94654bc 100644 --- a/crates/rome_js_formatter/src/js/any/class_member.rs +++ b/crates/rome_js_formatter/src/js/any/class_member.rs @@ -5,38 +5,22 @@ use crate::prelude::*; use rome_js_syntax::JsAnyClassMember; impl FormatRule for FormatJsAnyClassMember { type Context = JsFormatContext; - fn format(node: &JsAnyClassMember, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsAnyClassMember, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyClassMember::JsConstructorClassMember(node) => { - formatted![formatter, [node.format()]] - } - JsAnyClassMember::JsStaticInitializationBlockClassMember(node) => { - formatted![formatter, [node.format()]] - } - JsAnyClassMember::JsPropertyClassMember(node) => formatted![formatter, [node.format()]], - JsAnyClassMember::JsMethodClassMember(node) => formatted![formatter, [node.format()]], - JsAnyClassMember::JsGetterClassMember(node) => formatted![formatter, [node.format()]], - JsAnyClassMember::JsSetterClassMember(node) => formatted![formatter, [node.format()]], - JsAnyClassMember::TsConstructorSignatureClassMember(node) => { - formatted![formatter, [node.format()]] - } - JsAnyClassMember::TsPropertySignatureClassMember(node) => { - formatted![formatter, [node.format()]] - } - JsAnyClassMember::TsMethodSignatureClassMember(node) => { - formatted![formatter, [node.format()]] - } - JsAnyClassMember::TsGetterSignatureClassMember(node) => { - formatted![formatter, [node.format()]] - } - JsAnyClassMember::TsSetterSignatureClassMember(node) => { - formatted![formatter, [node.format()]] - } - JsAnyClassMember::TsIndexSignatureClassMember(node) => { - formatted![formatter, [node.format()]] - } - JsAnyClassMember::JsEmptyClassMember(node) => formatted![formatter, [node.format()]], - JsAnyClassMember::JsUnknownMember(node) => formatted![formatter, [node.format()]], + JsAnyClassMember::JsConstructorClassMember(node) => node.format().fmt(f), + JsAnyClassMember::JsStaticInitializationBlockClassMember(node) => node.format().fmt(f), + JsAnyClassMember::JsPropertyClassMember(node) => node.format().fmt(f), + JsAnyClassMember::JsMethodClassMember(node) => node.format().fmt(f), + JsAnyClassMember::JsGetterClassMember(node) => node.format().fmt(f), + JsAnyClassMember::JsSetterClassMember(node) => node.format().fmt(f), + JsAnyClassMember::TsConstructorSignatureClassMember(node) => node.format().fmt(f), + JsAnyClassMember::TsPropertySignatureClassMember(node) => node.format().fmt(f), + JsAnyClassMember::TsMethodSignatureClassMember(node) => node.format().fmt(f), + JsAnyClassMember::TsGetterSignatureClassMember(node) => node.format().fmt(f), + JsAnyClassMember::TsSetterSignatureClassMember(node) => node.format().fmt(f), + JsAnyClassMember::TsIndexSignatureClassMember(node) => node.format().fmt(f), + JsAnyClassMember::JsEmptyClassMember(node) => node.format().fmt(f), + JsAnyClassMember::JsUnknownMember(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/class_member_name.rs b/crates/rome_js_formatter/src/js/any/class_member_name.rs index a95ff6754dd..89eb974a946 100644 --- a/crates/rome_js_formatter/src/js/any/class_member_name.rs +++ b/crates/rome_js_formatter/src/js/any/class_member_name.rs @@ -5,17 +5,11 @@ use crate::prelude::*; use rome_js_syntax::JsAnyClassMemberName; impl FormatRule for FormatJsAnyClassMemberName { type Context = JsFormatContext; - fn format(node: &JsAnyClassMemberName, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsAnyClassMemberName, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyClassMemberName::JsLiteralMemberName(node) => { - formatted![formatter, [node.format()]] - } - JsAnyClassMemberName::JsComputedMemberName(node) => { - formatted![formatter, [node.format()]] - } - JsAnyClassMemberName::JsPrivateClassMemberName(node) => { - formatted![formatter, [node.format()]] - } + JsAnyClassMemberName::JsLiteralMemberName(node) => node.format().fmt(f), + JsAnyClassMemberName::JsComputedMemberName(node) => node.format().fmt(f), + JsAnyClassMemberName::JsPrivateClassMemberName(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/constructor_parameter.rs b/crates/rome_js_formatter/src/js/any/constructor_parameter.rs index abff46db6bb..53ae4c6998e 100644 --- a/crates/rome_js_formatter/src/js/any/constructor_parameter.rs +++ b/crates/rome_js_formatter/src/js/any/constructor_parameter.rs @@ -5,20 +5,11 @@ use crate::prelude::*; use rome_js_syntax::JsAnyConstructorParameter; impl FormatRule for FormatJsAnyConstructorParameter { type Context = JsFormatContext; - fn format( - node: &JsAnyConstructorParameter, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt(node: &JsAnyConstructorParameter, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyConstructorParameter::JsAnyFormalParameter(node) => { - formatted![formatter, [node.format()]] - } - JsAnyConstructorParameter::JsRestParameter(node) => { - formatted![formatter, [node.format()]] - } - JsAnyConstructorParameter::TsPropertyParameter(node) => { - formatted![formatter, [node.format()]] - } + JsAnyConstructorParameter::JsAnyFormalParameter(node) => node.format().fmt(f), + JsAnyConstructorParameter::JsRestParameter(node) => node.format().fmt(f), + JsAnyConstructorParameter::TsPropertyParameter(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/declaration.rs b/crates/rome_js_formatter/src/js/any/declaration.rs index bdc87e21123..e256db1c09a 100644 --- a/crates/rome_js_formatter/src/js/any/declaration.rs +++ b/crates/rome_js_formatter/src/js/any/declaration.rs @@ -5,29 +5,19 @@ use crate::prelude::*; use rome_js_syntax::JsAnyDeclaration; impl FormatRule for FormatJsAnyDeclaration { type Context = JsFormatContext; - fn format(node: &JsAnyDeclaration, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsAnyDeclaration, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyDeclaration::JsClassDeclaration(node) => formatted![formatter, [node.format()]], - JsAnyDeclaration::JsFunctionDeclaration(node) => formatted![formatter, [node.format()]], - JsAnyDeclaration::JsVariableDeclaration(node) => formatted![formatter, [node.format()]], - JsAnyDeclaration::TsEnumDeclaration(node) => formatted![formatter, [node.format()]], - JsAnyDeclaration::TsTypeAliasDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyDeclaration::TsInterfaceDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyDeclaration::TsDeclareFunctionDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyDeclaration::TsModuleDeclaration(node) => formatted![formatter, [node.format()]], - JsAnyDeclaration::TsExternalModuleDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyDeclaration::TsGlobalDeclaration(node) => formatted![formatter, [node.format()]], - JsAnyDeclaration::TsImportEqualsDeclaration(node) => { - formatted![formatter, [node.format()]] - } + JsAnyDeclaration::JsClassDeclaration(node) => node.format().fmt(f), + JsAnyDeclaration::JsFunctionDeclaration(node) => node.format().fmt(f), + JsAnyDeclaration::JsVariableDeclaration(node) => node.format().fmt(f), + JsAnyDeclaration::TsEnumDeclaration(node) => node.format().fmt(f), + JsAnyDeclaration::TsTypeAliasDeclaration(node) => node.format().fmt(f), + JsAnyDeclaration::TsInterfaceDeclaration(node) => node.format().fmt(f), + JsAnyDeclaration::TsDeclareFunctionDeclaration(node) => node.format().fmt(f), + JsAnyDeclaration::TsModuleDeclaration(node) => node.format().fmt(f), + JsAnyDeclaration::TsExternalModuleDeclaration(node) => node.format().fmt(f), + JsAnyDeclaration::TsGlobalDeclaration(node) => node.format().fmt(f), + JsAnyDeclaration::TsImportEqualsDeclaration(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/declaration_clause.rs b/crates/rome_js_formatter/src/js/any/declaration_clause.rs index 9e8e960ebc2..b23c0c27ce3 100644 --- a/crates/rome_js_formatter/src/js/any/declaration_clause.rs +++ b/crates/rome_js_formatter/src/js/any/declaration_clause.rs @@ -5,44 +5,19 @@ use crate::prelude::*; use rome_js_syntax::JsAnyDeclarationClause; impl FormatRule for FormatJsAnyDeclarationClause { type Context = JsFormatContext; - fn format( - node: &JsAnyDeclarationClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt(node: &JsAnyDeclarationClause, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyDeclarationClause::JsClassDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyDeclarationClause::JsFunctionDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyDeclarationClause::JsVariableDeclarationClause(node) => { - formatted![formatter, [node.format()]] - } - JsAnyDeclarationClause::TsEnumDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyDeclarationClause::TsTypeAliasDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyDeclarationClause::TsInterfaceDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyDeclarationClause::TsDeclareFunctionDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyDeclarationClause::TsModuleDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyDeclarationClause::TsExternalModuleDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyDeclarationClause::TsGlobalDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyDeclarationClause::TsImportEqualsDeclaration(node) => { - formatted![formatter, [node.format()]] - } + JsAnyDeclarationClause::JsClassDeclaration(node) => node.format().fmt(f), + JsAnyDeclarationClause::JsFunctionDeclaration(node) => node.format().fmt(f), + JsAnyDeclarationClause::JsVariableDeclarationClause(node) => node.format().fmt(f), + JsAnyDeclarationClause::TsEnumDeclaration(node) => node.format().fmt(f), + JsAnyDeclarationClause::TsTypeAliasDeclaration(node) => node.format().fmt(f), + JsAnyDeclarationClause::TsInterfaceDeclaration(node) => node.format().fmt(f), + JsAnyDeclarationClause::TsDeclareFunctionDeclaration(node) => node.format().fmt(f), + JsAnyDeclarationClause::TsModuleDeclaration(node) => node.format().fmt(f), + JsAnyDeclarationClause::TsExternalModuleDeclaration(node) => node.format().fmt(f), + JsAnyDeclarationClause::TsGlobalDeclaration(node) => node.format().fmt(f), + JsAnyDeclarationClause::TsImportEqualsDeclaration(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/export_clause.rs b/crates/rome_js_formatter/src/js/any/export_clause.rs index 683e81ced89..e87aaff182e 100644 --- a/crates/rome_js_formatter/src/js/any/export_clause.rs +++ b/crates/rome_js_formatter/src/js/any/export_clause.rs @@ -5,31 +5,17 @@ use crate::prelude::*; use rome_js_syntax::JsAnyExportClause; impl FormatRule for FormatJsAnyExportClause { type Context = JsFormatContext; - fn format(node: &JsAnyExportClause, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsAnyExportClause, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyExportClause::JsExportDefaultDeclarationClause(node) => { - formatted![formatter, [node.format()]] - } - JsAnyExportClause::JsExportDefaultExpressionClause(node) => { - formatted![formatter, [node.format()]] - } - JsAnyExportClause::JsExportNamedClause(node) => formatted![formatter, [node.format()]], - JsAnyExportClause::JsExportFromClause(node) => formatted![formatter, [node.format()]], - JsAnyExportClause::JsExportNamedFromClause(node) => { - formatted![formatter, [node.format()]] - } - JsAnyExportClause::JsAnyDeclarationClause(node) => { - formatted![formatter, [node.format()]] - } - JsAnyExportClause::TsExportAsNamespaceClause(node) => { - formatted![formatter, [node.format()]] - } - JsAnyExportClause::TsExportAssignmentClause(node) => { - formatted![formatter, [node.format()]] - } - JsAnyExportClause::TsExportDeclareClause(node) => { - formatted![formatter, [node.format()]] - } + JsAnyExportClause::JsExportDefaultDeclarationClause(node) => node.format().fmt(f), + JsAnyExportClause::JsExportDefaultExpressionClause(node) => node.format().fmt(f), + JsAnyExportClause::JsExportNamedClause(node) => node.format().fmt(f), + JsAnyExportClause::JsExportFromClause(node) => node.format().fmt(f), + JsAnyExportClause::JsExportNamedFromClause(node) => node.format().fmt(f), + JsAnyExportClause::JsAnyDeclarationClause(node) => node.format().fmt(f), + JsAnyExportClause::TsExportAsNamespaceClause(node) => node.format().fmt(f), + JsAnyExportClause::TsExportAssignmentClause(node) => node.format().fmt(f), + JsAnyExportClause::TsExportDeclareClause(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/export_default_declaration.rs b/crates/rome_js_formatter/src/js/any/export_default_declaration.rs index 8b15f2177e5..06b107a0afe 100644 --- a/crates/rome_js_formatter/src/js/any/export_default_declaration.rs +++ b/crates/rome_js_formatter/src/js/any/export_default_declaration.rs @@ -5,23 +5,18 @@ use crate::prelude::*; use rome_js_syntax::JsAnyExportDefaultDeclaration; impl FormatRule for FormatJsAnyExportDefaultDeclaration { type Context = JsFormatContext; - fn format( - node: &JsAnyExportDefaultDeclaration, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt(node: &JsAnyExportDefaultDeclaration, f: &mut JsFormatter) -> FormatResult<()> { match node { JsAnyExportDefaultDeclaration::JsClassExportDefaultDeclaration(node) => { - formatted![formatter, [node.format()]] + node.format().fmt(f) } JsAnyExportDefaultDeclaration::JsFunctionExportDefaultDeclaration(node) => { - formatted![formatter, [node.format()]] + node.format().fmt(f) } JsAnyExportDefaultDeclaration::TsDeclareFunctionDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyExportDefaultDeclaration::TsInterfaceDeclaration(node) => { - formatted![formatter, [node.format()]] + node.format().fmt(f) } + JsAnyExportDefaultDeclaration::TsInterfaceDeclaration(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/export_named_specifier.rs b/crates/rome_js_formatter/src/js/any/export_named_specifier.rs index f93f62b4791..061cc62a05e 100644 --- a/crates/rome_js_formatter/src/js/any/export_named_specifier.rs +++ b/crates/rome_js_formatter/src/js/any/export_named_specifier.rs @@ -5,17 +5,12 @@ use crate::prelude::*; use rome_js_syntax::JsAnyExportNamedSpecifier; impl FormatRule for FormatJsAnyExportNamedSpecifier { type Context = JsFormatContext; - fn format( - node: &JsAnyExportNamedSpecifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt(node: &JsAnyExportNamedSpecifier, f: &mut JsFormatter) -> FormatResult<()> { match node { JsAnyExportNamedSpecifier::JsExportNamedShorthandSpecifier(node) => { - formatted![formatter, [node.format()]] - } - JsAnyExportNamedSpecifier::JsExportNamedSpecifier(node) => { - formatted![formatter, [node.format()]] + node.format().fmt(f) } + JsAnyExportNamedSpecifier::JsExportNamedSpecifier(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/expression.rs b/crates/rome_js_formatter/src/js/any/expression.rs index d352041e4e7..3e23ccbd0ab 100644 --- a/crates/rome_js_formatter/src/js/any/expression.rs +++ b/crates/rome_js_formatter/src/js/any/expression.rs @@ -5,57 +5,43 @@ use crate::prelude::*; use rome_js_syntax::JsAnyExpression; impl FormatRule for FormatJsAnyExpression { type Context = JsFormatContext; - fn format(node: &JsAnyExpression, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsAnyExpression, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyExpression::JsAnyLiteralExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::ImportMeta(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsArrayExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsArrowFunctionExpression(node) => { - formatted![formatter, [node.format()]] - } - JsAnyExpression::JsAssignmentExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsAwaitExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsBinaryExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsCallExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsClassExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsComputedMemberExpression(node) => { - formatted![formatter, [node.format()]] - } - JsAnyExpression::JsConditionalExpression(node) => { - formatted![formatter, [node.format()]] - } - JsAnyExpression::JsFunctionExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsIdentifierExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsImportCallExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsInExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsInstanceofExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsLogicalExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsNewExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsObjectExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsParenthesizedExpression(node) => { - formatted![formatter, [node.format()]] - } - JsAnyExpression::JsPostUpdateExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsPreUpdateExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsSequenceExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsStaticMemberExpression(node) => { - formatted![formatter, [node.format()]] - } - JsAnyExpression::JsSuperExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsThisExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsUnaryExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsUnknownExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsYieldExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::NewTarget(node) => formatted![formatter, [node.format()]], - JsAnyExpression::JsTemplate(node) => formatted![formatter, [node.format()]], - JsAnyExpression::TsTypeAssertionExpression(node) => { - formatted![formatter, [node.format()]] - } - JsAnyExpression::TsAsExpression(node) => formatted![formatter, [node.format()]], - JsAnyExpression::TsNonNullAssertionExpression(node) => { - formatted![formatter, [node.format()]] - } - JsAnyExpression::JsxTagExpression(node) => formatted![formatter, [node.format()]], + JsAnyExpression::JsAnyLiteralExpression(node) => node.format().fmt(f), + JsAnyExpression::ImportMeta(node) => node.format().fmt(f), + JsAnyExpression::JsArrayExpression(node) => node.format().fmt(f), + JsAnyExpression::JsArrowFunctionExpression(node) => node.format().fmt(f), + JsAnyExpression::JsAssignmentExpression(node) => node.format().fmt(f), + JsAnyExpression::JsAwaitExpression(node) => node.format().fmt(f), + JsAnyExpression::JsBinaryExpression(node) => node.format().fmt(f), + JsAnyExpression::JsCallExpression(node) => node.format().fmt(f), + JsAnyExpression::JsClassExpression(node) => node.format().fmt(f), + JsAnyExpression::JsComputedMemberExpression(node) => node.format().fmt(f), + JsAnyExpression::JsConditionalExpression(node) => node.format().fmt(f), + JsAnyExpression::JsFunctionExpression(node) => node.format().fmt(f), + JsAnyExpression::JsIdentifierExpression(node) => node.format().fmt(f), + JsAnyExpression::JsImportCallExpression(node) => node.format().fmt(f), + JsAnyExpression::JsInExpression(node) => node.format().fmt(f), + JsAnyExpression::JsInstanceofExpression(node) => node.format().fmt(f), + JsAnyExpression::JsLogicalExpression(node) => node.format().fmt(f), + JsAnyExpression::JsNewExpression(node) => node.format().fmt(f), + JsAnyExpression::JsObjectExpression(node) => node.format().fmt(f), + JsAnyExpression::JsParenthesizedExpression(node) => node.format().fmt(f), + JsAnyExpression::JsPostUpdateExpression(node) => node.format().fmt(f), + JsAnyExpression::JsPreUpdateExpression(node) => node.format().fmt(f), + JsAnyExpression::JsSequenceExpression(node) => node.format().fmt(f), + JsAnyExpression::JsStaticMemberExpression(node) => node.format().fmt(f), + JsAnyExpression::JsSuperExpression(node) => node.format().fmt(f), + JsAnyExpression::JsThisExpression(node) => node.format().fmt(f), + JsAnyExpression::JsUnaryExpression(node) => node.format().fmt(f), + JsAnyExpression::JsUnknownExpression(node) => node.format().fmt(f), + JsAnyExpression::JsYieldExpression(node) => node.format().fmt(f), + JsAnyExpression::NewTarget(node) => node.format().fmt(f), + JsAnyExpression::JsTemplate(node) => node.format().fmt(f), + JsAnyExpression::TsTypeAssertionExpression(node) => node.format().fmt(f), + JsAnyExpression::TsAsExpression(node) => node.format().fmt(f), + JsAnyExpression::TsNonNullAssertionExpression(node) => node.format().fmt(f), + JsAnyExpression::JsxTagExpression(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/for_in_or_of_initializer.rs b/crates/rome_js_formatter/src/js/any/for_in_or_of_initializer.rs index 4d9a97adc18..8870f4f43cc 100644 --- a/crates/rome_js_formatter/src/js/any/for_in_or_of_initializer.rs +++ b/crates/rome_js_formatter/src/js/any/for_in_or_of_initializer.rs @@ -5,17 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsAnyForInOrOfInitializer; impl FormatRule for FormatJsAnyForInOrOfInitializer { type Context = JsFormatContext; - fn format( - node: &JsAnyForInOrOfInitializer, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt(node: &JsAnyForInOrOfInitializer, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyForInOrOfInitializer::JsAnyAssignmentPattern(node) => { - formatted![formatter, [node.format()]] - } - JsAnyForInOrOfInitializer::JsForVariableDeclaration(node) => { - formatted![formatter, [node.format()]] - } + JsAnyForInOrOfInitializer::JsAnyAssignmentPattern(node) => node.format().fmt(f), + JsAnyForInOrOfInitializer::JsForVariableDeclaration(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/for_initializer.rs b/crates/rome_js_formatter/src/js/any/for_initializer.rs index 3fdf3c02c3b..0414467a8b1 100644 --- a/crates/rome_js_formatter/src/js/any/for_initializer.rs +++ b/crates/rome_js_formatter/src/js/any/for_initializer.rs @@ -5,12 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsAnyForInitializer; impl FormatRule for FormatJsAnyForInitializer { type Context = JsFormatContext; - fn format(node: &JsAnyForInitializer, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsAnyForInitializer, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyForInitializer::JsVariableDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyForInitializer::JsAnyExpression(node) => formatted![formatter, [node.format()]], + JsAnyForInitializer::JsVariableDeclaration(node) => node.format().fmt(f), + JsAnyForInitializer::JsAnyExpression(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/formal_parameter.rs b/crates/rome_js_formatter/src/js/any/formal_parameter.rs index 7ab482a4fbe..241ce4426d7 100644 --- a/crates/rome_js_formatter/src/js/any/formal_parameter.rs +++ b/crates/rome_js_formatter/src/js/any/formal_parameter.rs @@ -5,12 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsAnyFormalParameter; impl FormatRule for FormatJsAnyFormalParameter { type Context = JsFormatContext; - fn format(node: &JsAnyFormalParameter, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsAnyFormalParameter, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyFormalParameter::JsFormalParameter(node) => formatted![formatter, [node.format()]], - JsAnyFormalParameter::JsUnknownParameter(node) => { - formatted![formatter, [node.format()]] - } + JsAnyFormalParameter::JsFormalParameter(node) => node.format().fmt(f), + JsAnyFormalParameter::JsUnknownParameter(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/function.rs b/crates/rome_js_formatter/src/js/any/function.rs index dc1d1149583..3b670c61808 100644 --- a/crates/rome_js_formatter/src/js/any/function.rs +++ b/crates/rome_js_formatter/src/js/any/function.rs @@ -1,7 +1,7 @@ -use crate::prelude::*; - use crate::generated::FormatJsAnyFunction; +use crate::prelude::*; use crate::utils::is_simple_expression; +use rome_formatter::{format_args, write}; use rome_js_syntax::{ JsAnyArrowFunctionParameters, JsAnyExpression, JsAnyFunction, JsAnyFunctionBody, }; @@ -9,56 +9,45 @@ use rome_js_syntax::{ impl FormatRule for FormatJsAnyFunction { type Context = JsFormatContext; - fn format(node: &JsAnyFunction, formatter: &JsFormatter) -> FormatResult { - let mut tokens = vec![]; - - tokens.push(formatted![ - formatter, - [node - .async_token() - .format() - .with_or_empty(|token| { formatted![formatter, [token, space_token()]] })] - ]?); + fn fmt(node: &JsAnyFunction, f: &mut JsFormatter) -> FormatResult<()> { + if let Some(async_token) = node.async_token() { + write!(f, [async_token.format(), space_token()])?; + } - tokens.push(formatted![formatter, [node.function_token().format()]]?); - tokens.push(formatted![formatter, [node.star_token().format()]]?); + write!( + f, + [node.function_token().format(), node.star_token().format()] + )?; - tokens.push(match node { - JsAnyFunction::JsArrowFunctionExpression(_) => empty_element(), - _ => formatted![ - formatter, - [node - .id() - .format() - .with_or(|id| formatted![formatter, [space_token(), id]], space_token,)] - ]?, - }); + if !matches!(node, JsAnyFunction::JsArrowFunctionExpression(_)) { + match node.id()? { + Some(id) => { + write!(f, [space_token(), id.format()])?; + } + None => { + write!(f, [space_token()])?; + } + } + } - tokens.push(formatted![formatter, [node.type_parameters().format()]]?); + write!(f, [node.type_parameters().format()])?; - tokens.push(match node.parameters()? { - JsAnyArrowFunctionParameters::JsAnyBinding(binding) => group_elements(formatted![ - formatter, - [ + match node.parameters()? { + JsAnyArrowFunctionParameters::JsAnyBinding(binding) => write!( + f, + [group_elements(&format_args![ token("("), - soft_block_indent(formatted![ - formatter, - [binding.format(), if_group_breaks(token(",")),] - ]?), + soft_block_indent(&format_args![ + binding.format(), + if_group_breaks(&token(",")), + ]), token(")"), - ] - ]?), - JsAnyArrowFunctionParameters::JsParameters(params) => { - formatted![formatter, [params.format()]]? - } - }); - - tokens.push(formatted![ - formatter, - [node.return_type_annotation().format()] - ]?); + ])] + )?, + JsAnyArrowFunctionParameters::JsParameters(params) => write![f, [params.format()]]?, + } - tokens.push(space_token()); + write![f, [node.return_type_annotation().format(), space_token()]]?; // We create a new group for everything after the parameters. That way if the parameters // get broken, we don't line break the arrow and the body if they can fit on the same line. @@ -73,10 +62,7 @@ impl FormatRule for FormatJsAnyFunction { // The line break for `a + b` is not necessary // if let JsAnyFunction::JsArrowFunctionExpression(arrow) = node { - tokens.push(formatted![ - formatter, - [arrow.fat_arrow_token().format(), space_token()] - ]?); + write![f, [arrow.fat_arrow_token().format(), space_token()]]?; } let body = node.body()?; @@ -110,14 +96,16 @@ impl FormatRule for FormatJsAnyFunction { }; if body_has_soft_line_break { - tokens.push(formatted![formatter, [node.body().format()]]?); + write![f, [node.body().format()]]?; } else { - tokens.push(group_elements(soft_line_indent_or_space(formatted![ - formatter, - [node.body().format()] - ]?))); + write!( + f, + [group_elements(&soft_line_indent_or_space( + &node.body().format() + ))] + )?; } - Ok(concat_elements(tokens)) + Ok(()) } } diff --git a/crates/rome_js_formatter/src/js/any/function_body.rs b/crates/rome_js_formatter/src/js/any/function_body.rs index e3735cbd9e1..a7e3cb408cd 100644 --- a/crates/rome_js_formatter/src/js/any/function_body.rs +++ b/crates/rome_js_formatter/src/js/any/function_body.rs @@ -5,10 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsAnyFunctionBody; impl FormatRule for FormatJsAnyFunctionBody { type Context = JsFormatContext; - fn format(node: &JsAnyFunctionBody, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsAnyFunctionBody, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyFunctionBody::JsAnyExpression(node) => formatted![formatter, [node.format()]], - JsAnyFunctionBody::JsFunctionBody(node) => formatted![formatter, [node.format()]], + JsAnyFunctionBody::JsAnyExpression(node) => node.format().fmt(f), + JsAnyFunctionBody::JsFunctionBody(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/import_assertion_entry.rs b/crates/rome_js_formatter/src/js/any/import_assertion_entry.rs index dc51fc94bb4..d3e9ba7219e 100644 --- a/crates/rome_js_formatter/src/js/any/import_assertion_entry.rs +++ b/crates/rome_js_formatter/src/js/any/import_assertion_entry.rs @@ -5,17 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsAnyImportAssertionEntry; impl FormatRule for FormatJsAnyImportAssertionEntry { type Context = JsFormatContext; - fn format( - node: &JsAnyImportAssertionEntry, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt(node: &JsAnyImportAssertionEntry, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyImportAssertionEntry::JsImportAssertionEntry(node) => { - formatted![formatter, [node.format()]] - } - JsAnyImportAssertionEntry::JsUnknownImportAssertionEntry(node) => { - formatted![formatter, [node.format()]] - } + JsAnyImportAssertionEntry::JsImportAssertionEntry(node) => node.format().fmt(f), + JsAnyImportAssertionEntry::JsUnknownImportAssertionEntry(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/import_clause.rs b/crates/rome_js_formatter/src/js/any/import_clause.rs index 52edd35406e..489b5ccded8 100644 --- a/crates/rome_js_formatter/src/js/any/import_clause.rs +++ b/crates/rome_js_formatter/src/js/any/import_clause.rs @@ -5,16 +5,12 @@ use crate::prelude::*; use rome_js_syntax::JsAnyImportClause; impl FormatRule for FormatJsAnyImportClause { type Context = JsFormatContext; - fn format(node: &JsAnyImportClause, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsAnyImportClause, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyImportClause::JsImportBareClause(node) => formatted![formatter, [node.format()]], - JsAnyImportClause::JsImportNamedClause(node) => formatted![formatter, [node.format()]], - JsAnyImportClause::JsImportDefaultClause(node) => { - formatted![formatter, [node.format()]] - } - JsAnyImportClause::JsImportNamespaceClause(node) => { - formatted![formatter, [node.format()]] - } + JsAnyImportClause::JsImportBareClause(node) => node.format().fmt(f), + JsAnyImportClause::JsImportNamedClause(node) => node.format().fmt(f), + JsAnyImportClause::JsImportDefaultClause(node) => node.format().fmt(f), + JsAnyImportClause::JsImportNamespaceClause(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/in_property.rs b/crates/rome_js_formatter/src/js/any/in_property.rs index fc682820c08..254407cd1f3 100644 --- a/crates/rome_js_formatter/src/js/any/in_property.rs +++ b/crates/rome_js_formatter/src/js/any/in_property.rs @@ -5,10 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsAnyInProperty; impl FormatRule for FormatJsAnyInProperty { type Context = JsFormatContext; - fn format(node: &JsAnyInProperty, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsAnyInProperty, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyInProperty::JsPrivateName(node) => formatted![formatter, [node.format()]], - JsAnyInProperty::JsAnyExpression(node) => formatted![formatter, [node.format()]], + JsAnyInProperty::JsPrivateName(node) => node.format().fmt(f), + JsAnyInProperty::JsAnyExpression(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/literal_expression.rs b/crates/rome_js_formatter/src/js/any/literal_expression.rs index df81549383f..698ff637fd1 100644 --- a/crates/rome_js_formatter/src/js/any/literal_expression.rs +++ b/crates/rome_js_formatter/src/js/any/literal_expression.rs @@ -5,29 +5,14 @@ use crate::prelude::*; use rome_js_syntax::JsAnyLiteralExpression; impl FormatRule for FormatJsAnyLiteralExpression { type Context = JsFormatContext; - fn format( - node: &JsAnyLiteralExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt(node: &JsAnyLiteralExpression, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyLiteralExpression::JsStringLiteralExpression(node) => { - formatted![formatter, [node.format()]] - } - JsAnyLiteralExpression::JsNumberLiteralExpression(node) => { - formatted![formatter, [node.format()]] - } - JsAnyLiteralExpression::JsBigIntLiteralExpression(node) => { - formatted![formatter, [node.format()]] - } - JsAnyLiteralExpression::JsBooleanLiteralExpression(node) => { - formatted![formatter, [node.format()]] - } - JsAnyLiteralExpression::JsNullLiteralExpression(node) => { - formatted![formatter, [node.format()]] - } - JsAnyLiteralExpression::JsRegexLiteralExpression(node) => { - formatted![formatter, [node.format()]] - } + JsAnyLiteralExpression::JsStringLiteralExpression(node) => node.format().fmt(f), + JsAnyLiteralExpression::JsNumberLiteralExpression(node) => node.format().fmt(f), + JsAnyLiteralExpression::JsBigIntLiteralExpression(node) => node.format().fmt(f), + JsAnyLiteralExpression::JsBooleanLiteralExpression(node) => node.format().fmt(f), + JsAnyLiteralExpression::JsNullLiteralExpression(node) => node.format().fmt(f), + JsAnyLiteralExpression::JsRegexLiteralExpression(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/method_modifier.rs b/crates/rome_js_formatter/src/js/any/method_modifier.rs index 3f34c3cf17c..05d97e4eac2 100644 --- a/crates/rome_js_formatter/src/js/any/method_modifier.rs +++ b/crates/rome_js_formatter/src/js/any/method_modifier.rs @@ -5,13 +5,11 @@ use crate::prelude::*; use rome_js_syntax::JsAnyMethodModifier; impl FormatRule for FormatJsAnyMethodModifier { type Context = JsFormatContext; - fn format(node: &JsAnyMethodModifier, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsAnyMethodModifier, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyMethodModifier::TsAccessibilityModifier(node) => { - formatted![formatter, [node.format()]] - } - JsAnyMethodModifier::JsStaticModifier(node) => formatted![formatter, [node.format()]], - JsAnyMethodModifier::TsOverrideModifier(node) => formatted![formatter, [node.format()]], + JsAnyMethodModifier::TsAccessibilityModifier(node) => node.format().fmt(f), + JsAnyMethodModifier::JsStaticModifier(node) => node.format().fmt(f), + JsAnyMethodModifier::TsOverrideModifier(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/module_item.rs b/crates/rome_js_formatter/src/js/any/module_item.rs index 6b848ee2d0b..e53454ccdf7 100644 --- a/crates/rome_js_formatter/src/js/any/module_item.rs +++ b/crates/rome_js_formatter/src/js/any/module_item.rs @@ -5,11 +5,11 @@ use crate::prelude::*; use rome_js_syntax::JsAnyModuleItem; impl FormatRule for FormatJsAnyModuleItem { type Context = JsFormatContext; - fn format(node: &JsAnyModuleItem, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsAnyModuleItem, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyModuleItem::JsAnyStatement(node) => formatted![formatter, [node.format()]], - JsAnyModuleItem::JsExport(node) => formatted![formatter, [node.format()]], - JsAnyModuleItem::JsImport(node) => formatted![formatter, [node.format()]], + JsAnyModuleItem::JsAnyStatement(node) => node.format().fmt(f), + JsAnyModuleItem::JsExport(node) => node.format().fmt(f), + JsAnyModuleItem::JsImport(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/name.rs b/crates/rome_js_formatter/src/js/any/name.rs index d84a462e54f..2ecdc7d2e07 100644 --- a/crates/rome_js_formatter/src/js/any/name.rs +++ b/crates/rome_js_formatter/src/js/any/name.rs @@ -5,10 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsAnyName; impl FormatRule for FormatJsAnyName { type Context = JsFormatContext; - fn format(node: &JsAnyName, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsAnyName, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyName::JsName(node) => formatted![formatter, [node.format()]], - JsAnyName::JsPrivateName(node) => formatted![formatter, [node.format()]], + JsAnyName::JsName(node) => node.format().fmt(f), + JsAnyName::JsPrivateName(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/named_import.rs b/crates/rome_js_formatter/src/js/any/named_import.rs index 926a39c6a39..c40655ce6e5 100644 --- a/crates/rome_js_formatter/src/js/any/named_import.rs +++ b/crates/rome_js_formatter/src/js/any/named_import.rs @@ -5,14 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsAnyNamedImport; impl FormatRule for FormatJsAnyNamedImport { type Context = JsFormatContext; - fn format(node: &JsAnyNamedImport, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsAnyNamedImport, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyNamedImport::JsNamedImportSpecifiers(node) => { - formatted![formatter, [node.format()]] - } - JsAnyNamedImport::JsNamespaceImportSpecifier(node) => { - formatted![formatter, [node.format()]] - } + JsAnyNamedImport::JsNamedImportSpecifiers(node) => node.format().fmt(f), + JsAnyNamedImport::JsNamespaceImportSpecifier(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/named_import_specifier.rs b/crates/rome_js_formatter/src/js/any/named_import_specifier.rs index 2cc3bca6a03..e38098ca5ce 100644 --- a/crates/rome_js_formatter/src/js/any/named_import_specifier.rs +++ b/crates/rome_js_formatter/src/js/any/named_import_specifier.rs @@ -5,20 +5,13 @@ use crate::prelude::*; use rome_js_syntax::JsAnyNamedImportSpecifier; impl FormatRule for FormatJsAnyNamedImportSpecifier { type Context = JsFormatContext; - fn format( - node: &JsAnyNamedImportSpecifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt(node: &JsAnyNamedImportSpecifier, f: &mut JsFormatter) -> FormatResult<()> { match node { JsAnyNamedImportSpecifier::JsShorthandNamedImportSpecifier(node) => { - formatted![formatter, [node.format()]] - } - JsAnyNamedImportSpecifier::JsNamedImportSpecifier(node) => { - formatted![formatter, [node.format()]] - } - JsAnyNamedImportSpecifier::JsUnknownNamedImportSpecifier(node) => { - formatted![formatter, [node.format()]] + node.format().fmt(f) } + JsAnyNamedImportSpecifier::JsNamedImportSpecifier(node) => node.format().fmt(f), + JsAnyNamedImportSpecifier::JsUnknownNamedImportSpecifier(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/object_assignment_pattern_member.rs b/crates/rome_js_formatter/src/js/any/object_assignment_pattern_member.rs index 0053ba8f59c..d9b1ca97dab 100644 --- a/crates/rome_js_formatter/src/js/any/object_assignment_pattern_member.rs +++ b/crates/rome_js_formatter/src/js/any/object_assignment_pattern_member.rs @@ -5,23 +5,18 @@ use crate::prelude::*; use rome_js_syntax::JsAnyObjectAssignmentPatternMember; impl FormatRule for FormatJsAnyObjectAssignmentPatternMember { type Context = JsFormatContext; - fn format( - node: &JsAnyObjectAssignmentPatternMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt(node: &JsAnyObjectAssignmentPatternMember, f: &mut JsFormatter) -> FormatResult<()> { match node { JsAnyObjectAssignmentPatternMember::JsObjectAssignmentPatternShorthandProperty( node, - ) => formatted![formatter, [node.format()]], + ) => node.format().fmt(f), JsAnyObjectAssignmentPatternMember::JsObjectAssignmentPatternProperty(node) => { - formatted![formatter, [node.format()]] + node.format().fmt(f) } JsAnyObjectAssignmentPatternMember::JsObjectAssignmentPatternRest(node) => { - formatted![formatter, [node.format()]] - } - JsAnyObjectAssignmentPatternMember::JsUnknownAssignment(node) => { - formatted![formatter, [node.format()]] + node.format().fmt(f) } + JsAnyObjectAssignmentPatternMember::JsUnknownAssignment(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/object_binding_pattern_member.rs b/crates/rome_js_formatter/src/js/any/object_binding_pattern_member.rs index 235c4244de1..f4c0e142abe 100644 --- a/crates/rome_js_formatter/src/js/any/object_binding_pattern_member.rs +++ b/crates/rome_js_formatter/src/js/any/object_binding_pattern_member.rs @@ -5,26 +5,19 @@ use crate::prelude::*; use rome_js_syntax::JsAnyObjectBindingPatternMember; impl FormatRule for FormatJsAnyObjectBindingPatternMember { type Context = JsFormatContext; - fn format( - node: &JsAnyObjectBindingPatternMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt(node: &JsAnyObjectBindingPatternMember, f: &mut JsFormatter) -> FormatResult<()> { match node { JsAnyObjectBindingPatternMember::JsObjectBindingPatternProperty(node) => { - formatted![formatter, [node.format()]] + node.format().fmt(f) } JsAnyObjectBindingPatternMember::JsObjectBindingPatternRest(node) => { - formatted![formatter, [node.format()]] + node.format().fmt(f) } JsAnyObjectBindingPatternMember::JsObjectBindingPatternShorthandProperty(node) => { - formatted![formatter, [node.format()]] - } - JsAnyObjectBindingPatternMember::JsIdentifierBinding(node) => { - formatted![formatter, [node.format()]] - } - JsAnyObjectBindingPatternMember::JsUnknownBinding(node) => { - formatted![formatter, [node.format()]] + node.format().fmt(f) } + JsAnyObjectBindingPatternMember::JsIdentifierBinding(node) => node.format().fmt(f), + JsAnyObjectBindingPatternMember::JsUnknownBinding(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/object_member.rs b/crates/rome_js_formatter/src/js/any/object_member.rs index 17c842d9f49..678b2882240 100644 --- a/crates/rome_js_formatter/src/js/any/object_member.rs +++ b/crates/rome_js_formatter/src/js/any/object_member.rs @@ -5,19 +5,15 @@ use crate::prelude::*; use rome_js_syntax::JsAnyObjectMember; impl FormatRule for FormatJsAnyObjectMember { type Context = JsFormatContext; - fn format(node: &JsAnyObjectMember, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsAnyObjectMember, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyObjectMember::JsPropertyObjectMember(node) => { - formatted![formatter, [node.format()]] - } - JsAnyObjectMember::JsMethodObjectMember(node) => formatted![formatter, [node.format()]], - JsAnyObjectMember::JsGetterObjectMember(node) => formatted![formatter, [node.format()]], - JsAnyObjectMember::JsSetterObjectMember(node) => formatted![formatter, [node.format()]], - JsAnyObjectMember::JsShorthandPropertyObjectMember(node) => { - formatted![formatter, [node.format()]] - } - JsAnyObjectMember::JsSpread(node) => formatted![formatter, [node.format()]], - JsAnyObjectMember::JsUnknownMember(node) => formatted![formatter, [node.format()]], + JsAnyObjectMember::JsPropertyObjectMember(node) => node.format().fmt(f), + JsAnyObjectMember::JsMethodObjectMember(node) => node.format().fmt(f), + JsAnyObjectMember::JsGetterObjectMember(node) => node.format().fmt(f), + JsAnyObjectMember::JsSetterObjectMember(node) => node.format().fmt(f), + JsAnyObjectMember::JsShorthandPropertyObjectMember(node) => node.format().fmt(f), + JsAnyObjectMember::JsSpread(node) => node.format().fmt(f), + JsAnyObjectMember::JsUnknownMember(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/object_member_name.rs b/crates/rome_js_formatter/src/js/any/object_member_name.rs index 2f5e3775d6f..53bedbf2238 100644 --- a/crates/rome_js_formatter/src/js/any/object_member_name.rs +++ b/crates/rome_js_formatter/src/js/any/object_member_name.rs @@ -5,17 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsAnyObjectMemberName; impl FormatRule for FormatJsAnyObjectMemberName { type Context = JsFormatContext; - fn format( - node: &JsAnyObjectMemberName, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt(node: &JsAnyObjectMemberName, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyObjectMemberName::JsLiteralMemberName(node) => { - formatted![formatter, [node.format()]] - } - JsAnyObjectMemberName::JsComputedMemberName(node) => { - formatted![formatter, [node.format()]] - } + JsAnyObjectMemberName::JsLiteralMemberName(node) => node.format().fmt(f), + JsAnyObjectMemberName::JsComputedMemberName(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/parameter.rs b/crates/rome_js_formatter/src/js/any/parameter.rs index edfba83b1e9..09ebb06ea34 100644 --- a/crates/rome_js_formatter/src/js/any/parameter.rs +++ b/crates/rome_js_formatter/src/js/any/parameter.rs @@ -5,11 +5,11 @@ use crate::prelude::*; use rome_js_syntax::JsAnyParameter; impl FormatRule for FormatJsAnyParameter { type Context = JsFormatContext; - fn format(node: &JsAnyParameter, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsAnyParameter, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyParameter::JsAnyFormalParameter(node) => formatted![formatter, [node.format()]], - JsAnyParameter::JsRestParameter(node) => formatted![formatter, [node.format()]], - JsAnyParameter::TsThisParameter(node) => formatted![formatter, [node.format()]], + JsAnyParameter::JsAnyFormalParameter(node) => node.format().fmt(f), + JsAnyParameter::JsRestParameter(node) => node.format().fmt(f), + JsAnyParameter::TsThisParameter(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/property_modifier.rs b/crates/rome_js_formatter/src/js/any/property_modifier.rs index 11760aaaa31..2e6b32ab886 100644 --- a/crates/rome_js_formatter/src/js/any/property_modifier.rs +++ b/crates/rome_js_formatter/src/js/any/property_modifier.rs @@ -5,21 +5,12 @@ use crate::prelude::*; use rome_js_syntax::JsAnyPropertyModifier; impl FormatRule for FormatJsAnyPropertyModifier { type Context = JsFormatContext; - fn format( - node: &JsAnyPropertyModifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt(node: &JsAnyPropertyModifier, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyPropertyModifier::TsAccessibilityModifier(node) => { - formatted![formatter, [node.format()]] - } - JsAnyPropertyModifier::JsStaticModifier(node) => formatted![formatter, [node.format()]], - JsAnyPropertyModifier::TsReadonlyModifier(node) => { - formatted![formatter, [node.format()]] - } - JsAnyPropertyModifier::TsOverrideModifier(node) => { - formatted![formatter, [node.format()]] - } + JsAnyPropertyModifier::TsAccessibilityModifier(node) => node.format().fmt(f), + JsAnyPropertyModifier::JsStaticModifier(node) => node.format().fmt(f), + JsAnyPropertyModifier::TsReadonlyModifier(node) => node.format().fmt(f), + JsAnyPropertyModifier::TsOverrideModifier(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/root.rs b/crates/rome_js_formatter/src/js/any/root.rs index 7d697990097..a6179bbb614 100644 --- a/crates/rome_js_formatter/src/js/any/root.rs +++ b/crates/rome_js_formatter/src/js/any/root.rs @@ -5,11 +5,11 @@ use crate::prelude::*; use rome_js_syntax::JsAnyRoot; impl FormatRule for FormatJsAnyRoot { type Context = JsFormatContext; - fn format(node: &JsAnyRoot, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsAnyRoot, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyRoot::JsScript(node) => formatted![formatter, [node.format()]], - JsAnyRoot::JsModule(node) => formatted![formatter, [node.format()]], - JsAnyRoot::JsExpressionSnipped(node) => formatted![formatter, [node.format()]], + JsAnyRoot::JsScript(node) => node.format().fmt(f), + JsAnyRoot::JsModule(node) => node.format().fmt(f), + JsAnyRoot::JsExpressionSnipped(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/statement.rs b/crates/rome_js_formatter/src/js/any/statement.rs index 030abd5a44d..b788fc30bbf 100644 --- a/crates/rome_js_formatter/src/js/any/statement.rs +++ b/crates/rome_js_formatter/src/js/any/statement.rs @@ -5,46 +5,40 @@ use crate::prelude::*; use rome_js_syntax::JsAnyStatement; impl FormatRule for FormatJsAnyStatement { type Context = JsFormatContext; - fn format(node: &JsAnyStatement, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsAnyStatement, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyStatement::JsBlockStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsBreakStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsClassDeclaration(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsContinueStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsDebuggerStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsDoWhileStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsEmptyStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsExpressionStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsForInStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsForOfStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsForStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsIfStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsLabeledStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsReturnStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsSwitchStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsThrowStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsTryFinallyStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsTryStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsUnknownStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsVariableStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsWhileStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsWithStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::JsFunctionDeclaration(node) => formatted![formatter, [node.format()]], - JsAnyStatement::TsEnumDeclaration(node) => formatted![formatter, [node.format()]], - JsAnyStatement::TsTypeAliasDeclaration(node) => formatted![formatter, [node.format()]], - JsAnyStatement::TsInterfaceDeclaration(node) => formatted![formatter, [node.format()]], - JsAnyStatement::TsDeclareFunctionDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyStatement::TsDeclareStatement(node) => formatted![formatter, [node.format()]], - JsAnyStatement::TsModuleDeclaration(node) => formatted![formatter, [node.format()]], - JsAnyStatement::TsExternalModuleDeclaration(node) => { - formatted![formatter, [node.format()]] - } - JsAnyStatement::TsGlobalDeclaration(node) => formatted![formatter, [node.format()]], - JsAnyStatement::TsImportEqualsDeclaration(node) => { - formatted![formatter, [node.format()]] - } + JsAnyStatement::JsBlockStatement(node) => node.format().fmt(f), + JsAnyStatement::JsBreakStatement(node) => node.format().fmt(f), + JsAnyStatement::JsClassDeclaration(node) => node.format().fmt(f), + JsAnyStatement::JsContinueStatement(node) => node.format().fmt(f), + JsAnyStatement::JsDebuggerStatement(node) => node.format().fmt(f), + JsAnyStatement::JsDoWhileStatement(node) => node.format().fmt(f), + JsAnyStatement::JsEmptyStatement(node) => node.format().fmt(f), + JsAnyStatement::JsExpressionStatement(node) => node.format().fmt(f), + JsAnyStatement::JsForInStatement(node) => node.format().fmt(f), + JsAnyStatement::JsForOfStatement(node) => node.format().fmt(f), + JsAnyStatement::JsForStatement(node) => node.format().fmt(f), + JsAnyStatement::JsIfStatement(node) => node.format().fmt(f), + JsAnyStatement::JsLabeledStatement(node) => node.format().fmt(f), + JsAnyStatement::JsReturnStatement(node) => node.format().fmt(f), + JsAnyStatement::JsSwitchStatement(node) => node.format().fmt(f), + JsAnyStatement::JsThrowStatement(node) => node.format().fmt(f), + JsAnyStatement::JsTryFinallyStatement(node) => node.format().fmt(f), + JsAnyStatement::JsTryStatement(node) => node.format().fmt(f), + JsAnyStatement::JsUnknownStatement(node) => node.format().fmt(f), + JsAnyStatement::JsVariableStatement(node) => node.format().fmt(f), + JsAnyStatement::JsWhileStatement(node) => node.format().fmt(f), + JsAnyStatement::JsWithStatement(node) => node.format().fmt(f), + JsAnyStatement::JsFunctionDeclaration(node) => node.format().fmt(f), + JsAnyStatement::TsEnumDeclaration(node) => node.format().fmt(f), + JsAnyStatement::TsTypeAliasDeclaration(node) => node.format().fmt(f), + JsAnyStatement::TsInterfaceDeclaration(node) => node.format().fmt(f), + JsAnyStatement::TsDeclareFunctionDeclaration(node) => node.format().fmt(f), + JsAnyStatement::TsDeclareStatement(node) => node.format().fmt(f), + JsAnyStatement::TsModuleDeclaration(node) => node.format().fmt(f), + JsAnyStatement::TsExternalModuleDeclaration(node) => node.format().fmt(f), + JsAnyStatement::TsGlobalDeclaration(node) => node.format().fmt(f), + JsAnyStatement::TsImportEqualsDeclaration(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/switch_clause.rs b/crates/rome_js_formatter/src/js/any/switch_clause.rs index 944efbb6ca5..7f69fb84f0c 100644 --- a/crates/rome_js_formatter/src/js/any/switch_clause.rs +++ b/crates/rome_js_formatter/src/js/any/switch_clause.rs @@ -5,10 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsAnySwitchClause; impl FormatRule for FormatJsAnySwitchClause { type Context = JsFormatContext; - fn format(node: &JsAnySwitchClause, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsAnySwitchClause, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnySwitchClause::JsCaseClause(node) => formatted![formatter, [node.format()]], - JsAnySwitchClause::JsDefaultClause(node) => formatted![formatter, [node.format()]], + JsAnySwitchClause::JsCaseClause(node) => node.format().fmt(f), + JsAnySwitchClause::JsDefaultClause(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/any/template_element.rs b/crates/rome_js_formatter/src/js/any/template_element.rs index ff583ae72ed..3ff11357974 100644 --- a/crates/rome_js_formatter/src/js/any/template_element.rs +++ b/crates/rome_js_formatter/src/js/any/template_element.rs @@ -5,12 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsAnyTemplateElement; impl FormatRule for FormatJsAnyTemplateElement { type Context = JsFormatContext; - fn format(node: &JsAnyTemplateElement, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsAnyTemplateElement, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsAnyTemplateElement::JsTemplateChunkElement(node) => { - formatted![formatter, [node.format()]] - } - JsAnyTemplateElement::JsTemplateElement(node) => formatted![formatter, [node.format()]], + JsAnyTemplateElement::JsTemplateChunkElement(node) => node.format().fmt(f), + JsAnyTemplateElement::JsTemplateElement(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/js/assignments/array_assignment_pattern.rs b/crates/rome_js_formatter/src/js/assignments/array_assignment_pattern.rs index c09840c79cf..fbc28169dc1 100644 --- a/crates/rome_js_formatter/src/js/assignments/array_assignment_pattern.rs +++ b/crates/rome_js_formatter/src/js/assignments/array_assignment_pattern.rs @@ -1,27 +1,23 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsArrayAssignmentPattern; use rome_js_syntax::JsArrayAssignmentPatternFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsArrayAssignmentPattern, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsArrayAssignmentPattern, f: &mut JsFormatter) -> FormatResult<()> { let JsArrayAssignmentPatternFields { l_brack_token, elements, r_brack_token, } = node.as_fields(); - formatter - .delimited( - &l_brack_token?, - formatted![formatter, [elements.format()]]?, - &r_brack_token?, - ) - .soft_block_indent() - .finish() + write!( + f, + [ + format_delimited(&l_brack_token?, &elements.format(), &r_brack_token?,) + .soft_block_indent() + ] + ) } } diff --git a/crates/rome_js_formatter/src/js/assignments/array_assignment_pattern_rest_element.rs b/crates/rome_js_formatter/src/js/assignments/array_assignment_pattern_rest_element.rs index 0eb58d7137a..558ea6bdef2 100644 --- a/crates/rome_js_formatter/src/js/assignments/array_assignment_pattern_rest_element.rs +++ b/crates/rome_js_formatter/src/js/assignments/array_assignment_pattern_rest_element.rs @@ -1,4 +1,5 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsArrayAssignmentPatternRestElement; @@ -7,15 +8,15 @@ use rome_js_syntax::JsArrayAssignmentPatternRestElementFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( + fn fmt_fields( node: &JsArrayAssignmentPatternRestElement, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut JsFormatter, + ) -> FormatResult<()> { let JsArrayAssignmentPatternRestElementFields { dotdotdot_token, pattern, } = node.as_fields(); - formatted![formatter, [dotdotdot_token.format(), pattern.format()]] + write!(f, [dotdotdot_token.format(), pattern.format()]) } } diff --git a/crates/rome_js_formatter/src/js/assignments/assignment_with_default.rs b/crates/rome_js_formatter/src/js/assignments/assignment_with_default.rs index a775d7ba2b9..01bfaa115fc 100644 --- a/crates/rome_js_formatter/src/js/assignments/assignment_with_default.rs +++ b/crates/rome_js_formatter/src/js/assignments/assignment_with_default.rs @@ -1,22 +1,20 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsAssignmentWithDefault; use rome_js_syntax::JsAssignmentWithDefaultFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsAssignmentWithDefault, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsAssignmentWithDefault, f: &mut JsFormatter) -> FormatResult<()> { let JsAssignmentWithDefaultFields { pattern, eq_token, default, } = node.as_fields(); - formatted![ - formatter, + write!( + f, [ pattern.format(), space_token(), @@ -24,6 +22,6 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsComputedMemberAssignment, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsComputedMemberAssignment, f: &mut JsFormatter) -> FormatResult<()> { let JsComputedMemberAssignmentFields { object, l_brack_token, @@ -16,14 +14,14 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsIdentifierAssignment, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsIdentifierAssignment, f: &mut JsFormatter) -> FormatResult<()> { let JsIdentifierAssignmentFields { name_token } = node.as_fields(); - formatted![formatter, [name_token.format()]] + write![f, [name_token.format()]] } } diff --git a/crates/rome_js_formatter/src/js/assignments/object_assignment_pattern.rs b/crates/rome_js_formatter/src/js/assignments/object_assignment_pattern.rs index 4c735588ec0..2e28e5a2926 100644 --- a/crates/rome_js_formatter/src/js/assignments/object_assignment_pattern.rs +++ b/crates/rome_js_formatter/src/js/assignments/object_assignment_pattern.rs @@ -1,26 +1,23 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsObjectAssignmentPattern; use rome_js_syntax::JsObjectAssignmentPatternFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsObjectAssignmentPattern, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsObjectAssignmentPattern, f: &mut JsFormatter) -> FormatResult<()> { let JsObjectAssignmentPatternFields { l_curly_token, properties, r_curly_token, } = node.as_fields(); - formatter - .delimited( - &l_curly_token?, - formatted![formatter, [properties.format()]]?, - &r_curly_token?, - ) - .soft_block_spaces() - .finish() + write!( + f, + [ + format_delimited(&l_curly_token?, &properties.format(), &r_curly_token?,) + .soft_block_spaces() + ] + ) } } diff --git a/crates/rome_js_formatter/src/js/assignments/object_assignment_pattern_property.rs b/crates/rome_js_formatter/src/js/assignments/object_assignment_pattern_property.rs index 0e3810f50d1..3823895d8ad 100644 --- a/crates/rome_js_formatter/src/js/assignments/object_assignment_pattern_property.rs +++ b/crates/rome_js_formatter/src/js/assignments/object_assignment_pattern_property.rs @@ -1,4 +1,6 @@ use crate::prelude::*; +use rome_formatter::write; + use crate::utils::FormatMemberName; use crate::FormatNodeFields; use rome_js_syntax::JsObjectAssignmentPatternProperty; @@ -7,10 +9,10 @@ use rome_js_syntax::JsObjectAssignmentPatternPropertyFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( + fn fmt_fields( node: &JsObjectAssignmentPatternProperty, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut JsFormatter, + ) -> FormatResult<()> { let JsObjectAssignmentPatternPropertyFields { member, colon_token, @@ -18,16 +20,20 @@ impl FormatNodeFields init, } = node.as_fields(); - formatted![ - formatter, + write!( + f, [ FormatMemberName::from(member?), colon_token.format(), space_token(), pattern.format(), - init.format() - .with_or_empty(|node| formatted![formatter, [space_token(), node]]), ] - ] + )?; + + if let Some(init) = init { + write!(f, [space_token(), init.format()])?; + } + + Ok(()) } } diff --git a/crates/rome_js_formatter/src/js/assignments/object_assignment_pattern_rest.rs b/crates/rome_js_formatter/src/js/assignments/object_assignment_pattern_rest.rs index e328005a19f..d8482c6f38e 100644 --- a/crates/rome_js_formatter/src/js/assignments/object_assignment_pattern_rest.rs +++ b/crates/rome_js_formatter/src/js/assignments/object_assignment_pattern_rest.rs @@ -1,4 +1,5 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsObjectAssignmentPatternRest; @@ -7,15 +8,12 @@ use rome_js_syntax::JsObjectAssignmentPatternRestFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsObjectAssignmentPatternRest, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsObjectAssignmentPatternRest, f: &mut JsFormatter) -> FormatResult<()> { let JsObjectAssignmentPatternRestFields { dotdotdot_token, target, } = node.as_fields(); - formatted![formatter, [dotdotdot_token.format(), target.format()?,]] + write!(f, [dotdotdot_token.format(), target.format()]) } } diff --git a/crates/rome_js_formatter/src/js/assignments/object_assignment_pattern_shorthand_property.rs b/crates/rome_js_formatter/src/js/assignments/object_assignment_pattern_shorthand_property.rs index 6de00d3bfd0..21ac8f4115c 100644 --- a/crates/rome_js_formatter/src/js/assignments/object_assignment_pattern_shorthand_property.rs +++ b/crates/rome_js_formatter/src/js/assignments/object_assignment_pattern_shorthand_property.rs @@ -1,4 +1,5 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsObjectAssignmentPatternShorthandProperty; @@ -7,20 +8,18 @@ use rome_js_syntax::JsObjectAssignmentPatternShorthandPropertyFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( + fn fmt_fields( node: &JsObjectAssignmentPatternShorthandProperty, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut JsFormatter, + ) -> FormatResult<()> { let JsObjectAssignmentPatternShorthandPropertyFields { identifier, init } = node.as_fields(); - formatted![ - formatter, - [ - identifier.format()?, - init.format() - .with_or_empty(|node| formatted![formatter, [space_token(), node]]) - ] - ] + write!(f, [identifier.format()?,])?; + + if let Some(init) = init { + write!(f, [space_token(), init.format()])?; + } + Ok(()) } } diff --git a/crates/rome_js_formatter/src/js/assignments/parenthesized_assignment.rs b/crates/rome_js_formatter/src/js/assignments/parenthesized_assignment.rs index 9b2e640998d..108089989b0 100644 --- a/crates/rome_js_formatter/src/js/assignments/parenthesized_assignment.rs +++ b/crates/rome_js_formatter/src/js/assignments/parenthesized_assignment.rs @@ -1,21 +1,19 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsParenthesizedAssignment; use rome_js_syntax::JsParenthesizedAssignmentFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsParenthesizedAssignment, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsParenthesizedAssignment, f: &mut JsFormatter) -> FormatResult<()> { let JsParenthesizedAssignmentFields { l_paren_token, assignment, r_paren_token, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ l_paren_token.format(), assignment.format(), diff --git a/crates/rome_js_formatter/src/js/assignments/static_member_assignment.rs b/crates/rome_js_formatter/src/js/assignments/static_member_assignment.rs index 44827bc5b66..3114e7882f1 100644 --- a/crates/rome_js_formatter/src/js/assignments/static_member_assignment.rs +++ b/crates/rome_js_formatter/src/js/assignments/static_member_assignment.rs @@ -1,22 +1,17 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsStaticMemberAssignment; use rome_js_syntax::JsStaticMemberAssignmentFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsStaticMemberAssignment, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsStaticMemberAssignment, f: &mut JsFormatter) -> FormatResult<()> { let JsStaticMemberAssignmentFields { object, dot_token, member, } = node.as_fields(); - formatted![ - formatter, - [object.format(), dot_token.format(), member.format(),] - ] + write![f, [object.format(), dot_token.format(), member.format(),]] } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/array_hole.rs b/crates/rome_js_formatter/src/js/auxiliary/array_hole.rs index eba22d0ea5f..63102880a14 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/array_hole.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/array_hole.rs @@ -4,7 +4,7 @@ use crate::FormatNodeFields; use rome_js_syntax::JsArrayHole; impl FormatNodeFields for FormatNodeRule { - fn format_fields(_: &JsArrayHole, _: &JsFormatter) -> FormatResult { - Ok(empty_element()) + fn fmt_fields(_: &JsArrayHole, _: &mut JsFormatter) -> FormatResult<()> { + Ok(()) } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/case_clause.rs b/crates/rome_js_formatter/src/js/auxiliary/case_clause.rs index a7fa42e30d8..7d81924c049 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/case_clause.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/case_clause.rs @@ -1,13 +1,13 @@ use crate::prelude::*; -use rome_js_syntax::JsAnyStatement; -use rome_rowan::AstNodeList; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; +use rome_js_syntax::JsAnyStatement; use rome_js_syntax::JsCaseClause; use rome_js_syntax::JsCaseClauseFields; +use rome_rowan::AstNodeList; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsCaseClause, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &JsCaseClause, f: &mut JsFormatter) -> FormatResult<()> { let JsCaseClauseFields { case_token, test, @@ -15,27 +15,37 @@ impl FormatNodeFields for FormatNodeRule { consequent, } = node.as_fields(); + write!( + f, + [ + case_token.format(), + space_token(), + test.format(), + colon_token.format() + ] + )?; + let is_first_child_block_stmt = matches!( consequent.iter().next(), Some(JsAnyStatement::JsBlockStatement(_)) ); - let case_word = case_token.format(); - let colon = colon_token.format(); - let test = test.format(); - let cons = formatter.format_list(&consequent); - let cons = if cons.is_empty() { + if consequent.is_empty() { // Skip inserting an indent block is the consequent is empty to print // the trailing comments for the case clause inline if there is no // block to push them into - hard_line_break() + return write!(f, [hard_line_break()]); } else if is_first_child_block_stmt { - formatted![formatter, [space_token(), cons]]? + write![f, [space_token(), consequent.format()]] } else { // no line break needed after because it is added by the indent in the switch statement - indent(formatted![formatter, [hard_line_break(), cons]]?) - }; - - formatted![formatter, [case_word, space_token(), test, colon, cons]] + write!( + f, + [indent(&format_args![ + hard_line_break(), + consequent.format() + ])] + ) + } } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/catch_clause.rs b/crates/rome_js_formatter/src/js/auxiliary/catch_clause.rs index 1dbbcbcd16e..28370f2b5d0 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/catch_clause.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/catch_clause.rs @@ -1,39 +1,23 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsCatchClause; use rome_js_syntax::JsCatchClauseFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsCatchClause, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &JsCatchClause, f: &mut JsFormatter) -> FormatResult<()> { let JsCatchClauseFields { catch_token, declaration, body, } = node.as_fields(); - formatted![ - formatter, - [declaration.format().with_or( - |declaration| { - formatted![ - formatter, - [ - catch_token.format(), - space_token(), - declaration, - space_token(), - body.format() - ] - ] - }, - || { - formatted![ - formatter, - [catch_token.format(), space_token(), body.format()] - ] - }, - )] - ] + write!(f, [catch_token.format(), space_token()])?; + + if let Some(declaration) = declaration { + write![f, [declaration.format(), space_token()]]?; + } + + write!(f, [body.format()]) } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/default_clause.rs b/crates/rome_js_formatter/src/js/auxiliary/default_clause.rs index b5ecf849f89..eb2e9d81ec4 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/default_clause.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/default_clause.rs @@ -1,15 +1,12 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsDefaultClause; use rome_js_syntax::{JsAnyStatement, JsDefaultClauseFields}; use rome_rowan::AstNodeList; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsDefaultClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsDefaultClause, f: &mut JsFormatter) -> FormatResult<()> { let JsDefaultClauseFields { default_token, colon_token, @@ -21,18 +18,24 @@ impl FormatNodeFields for FormatNodeRule { Some(JsAnyStatement::JsBlockStatement(_)) ); - let default = default_token.format(); - let colon = colon_token.format(); - let statements = formatter.format_list(&consequent); + write!( + f, + [default_token.format(), colon_token.format(), space_token()] + )?; - let formatted_cons = if statements.is_empty() { - hard_line_break() + if consequent.is_empty() { + write!(f, [hard_line_break()]) } else if first_child_is_block_stmt { - formatted![formatter, [space_token(), statements]]? + write!(f, [space_token(), consequent.format()]) } else { // no line break needed after because it is added by the indent in the switch statement - indent(formatted![formatter, [hard_line_break(), statements]]?) - }; - formatted![formatter, [default, colon, space_token(), formatted_cons]] + write!( + f, + [indent(&format_args!( + hard_line_break(), + consequent.format() + ))] + ) + } } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/directive.rs b/crates/rome_js_formatter/src/js/auxiliary/directive.rs index 2b46f52643f..24703b565c2 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/directive.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/directive.rs @@ -1,21 +1,24 @@ use crate::prelude::*; -use crate::utils::{format_with_semicolon, FormatLiteralStringToken, StringLiteralParentKind}; +use crate::utils::{FormatLiteralStringToken, FormatWithSemicolon, StringLiteralParentKind}; +use rome_formatter::write; + use crate::FormatNodeFields; use rome_js_syntax::JsDirective; use rome_js_syntax::JsDirectiveFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsDirective, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &JsDirective, f: &mut JsFormatter) -> FormatResult<()> { let JsDirectiveFields { value_token, semicolon_token, } = node.as_fields(); - format_with_semicolon( - formatter, - FormatLiteralStringToken::new(&value_token?, StringLiteralParentKind::Directive) - .format(formatter)?, - semicolon_token, + write!( + f, + [FormatWithSemicolon::new( + &FormatLiteralStringToken::new(&value_token?, StringLiteralParentKind::Directive), + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/else_clause.rs b/crates/rome_js_formatter/src/js/auxiliary/else_clause.rs index c16c8d04f0e..7774d27a271 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/else_clause.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/else_clause.rs @@ -1,19 +1,16 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsElseClause; use rome_js_syntax::JsElseClauseFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsElseClause, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &JsElseClause, f: &mut JsFormatter) -> FormatResult<()> { let JsElseClauseFields { else_token, alternate, } = node.as_fields(); - formatted![ - formatter, - [else_token.format(), space_token(), alternate.format(),] - ] + write![f, [else_token.format(), space_token(), alternate.format(),]] } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/expression_snipped.rs b/crates/rome_js_formatter/src/js/auxiliary/expression_snipped.rs index 25075b461df..a71615951bc 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/expression_snipped.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/expression_snipped.rs @@ -1,24 +1,21 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsExpressionSnipped; use rome_js_syntax::JsExpressionSnippedFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsExpressionSnipped, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsExpressionSnipped, f: &mut JsFormatter) -> FormatResult<()> { let JsExpressionSnippedFields { expression, eof_token, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ expression.format(), - formatter.format_replaced(&eof_token?, empty_element()), + format_replaced(&eof_token?, &empty_element()), ] ] } diff --git a/crates/rome_js_formatter/src/js/auxiliary/finally_clause.rs b/crates/rome_js_formatter/src/js/auxiliary/finally_clause.rs index 781358f55ea..ecd74e54f6f 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/finally_clause.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/finally_clause.rs @@ -1,22 +1,16 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsFinallyClause; use rome_js_syntax::JsFinallyClauseFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsFinallyClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsFinallyClause, f: &mut JsFormatter) -> FormatResult<()> { let JsFinallyClauseFields { finally_token, body, } = node.as_fields(); - formatted![ - formatter, - [finally_token.format(), space_token(), body.format()] - ] + write![f, [finally_token.format(), space_token(), body.format()]] } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/function_body.rs b/crates/rome_js_formatter/src/js/auxiliary/function_body.rs index eeec8987c80..f92d3cb2707 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/function_body.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/function_body.rs @@ -1,14 +1,11 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsFunctionBody; use rome_js_syntax::JsFunctionBodyFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsFunctionBody, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsFunctionBody, f: &mut JsFormatter) -> FormatResult<()> { let JsFunctionBodyFields { l_curly_token, directives, @@ -16,16 +13,14 @@ impl FormatNodeFields for FormatNodeRule { r_curly_token, } = node.as_fields(); - formatter - .delimited( + write!( + f, + [format_delimited( &l_curly_token?, - formatted![ - formatter, - [directives.format(), formatter.format_list(&statements),] - ]?, + &format_args![directives.format(), statements.format()], &r_curly_token?, ) - .block_indent() - .finish() + .block_indent()] + ) } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/initializer_clause.rs b/crates/rome_js_formatter/src/js/auxiliary/initializer_clause.rs index cc3a9c11102..848bfb59daf 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/initializer_clause.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/initializer_clause.rs @@ -1,22 +1,16 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsInitializerClause; use rome_js_syntax::JsInitializerClauseFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsInitializerClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsInitializerClause, f: &mut JsFormatter) -> FormatResult<()> { let JsInitializerClauseFields { eq_token, expression, } = node.as_fields(); - formatted![ - formatter, - [eq_token.format(), space_token(), expression.format()] - ] + write![f, [eq_token.format(), space_token(), expression.format()]] } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/module.rs b/crates/rome_js_formatter/src/js/auxiliary/module.rs index 5e000bab159..cbc074ffee7 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/module.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/module.rs @@ -1,12 +1,13 @@ use crate::prelude::*; -use crate::utils::format_interpreter; +use rome_formatter::write; +use crate::utils::FormatInterpreterToken; use crate::FormatNodeFields; use rome_js_syntax::JsModule; use rome_js_syntax::JsModuleFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsModule, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &JsModule, f: &mut JsFormatter) -> FormatResult<()> { let JsModuleFields { interpreter_token, directives, @@ -14,15 +15,21 @@ impl FormatNodeFields for FormatNodeRule { eof_token, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ - format_interpreter(interpreter_token, formatter)?, - directives.format(), - formatter.format_list(&items), - formatter.format_replaced(&eof_token?, empty_element()), + FormatInterpreterToken::new(interpreter_token.as_ref()), + directives.format() + ] + ]?; + + write!( + f, + [ + items.format(), + format_replaced(&eof_token?, &empty_element()), hard_line_break() ] - ] + ) } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/name.rs b/crates/rome_js_formatter/src/js/auxiliary/name.rs index bc66baebcd2..cd21c41e6d2 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/name.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/name.rs @@ -1,13 +1,13 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsName; use rome_js_syntax::JsNameFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsName, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &JsName, f: &mut JsFormatter) -> FormatResult<()> { let JsNameFields { value_token } = node.as_fields(); - formatted![formatter, [value_token.format()]] + write![f, [value_token.format()]] } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/new_target.rs b/crates/rome_js_formatter/src/js/auxiliary/new_target.rs index c967888c1df..e74436d39d6 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/new_target.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/new_target.rs @@ -1,19 +1,19 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::NewTarget; use rome_js_syntax::NewTargetFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &NewTarget, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &NewTarget, f: &mut JsFormatter) -> FormatResult<()> { let NewTargetFields { new_token, dot_token, target_token, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ new_token.format(), dot_token.format(), diff --git a/crates/rome_js_formatter/src/js/auxiliary/private_name.rs b/crates/rome_js_formatter/src/js/auxiliary/private_name.rs index d80cef61882..3aa40d681ba 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/private_name.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/private_name.rs @@ -1,16 +1,16 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsPrivateName; use rome_js_syntax::JsPrivateNameFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsPrivateName, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &JsPrivateName, f: &mut JsFormatter) -> FormatResult<()> { let JsPrivateNameFields { hash_token, value_token, } = node.as_fields(); - formatted![formatter, [hash_token.format(), value_token.format()]] + write![f, [hash_token.format(), value_token.format()]] } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/reference_identifier.rs b/crates/rome_js_formatter/src/js/auxiliary/reference_identifier.rs index 4445bf63f7d..47a7270a26a 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/reference_identifier.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/reference_identifier.rs @@ -1,16 +1,13 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsReferenceIdentifier; use rome_js_syntax::JsReferenceIdentifierFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsReferenceIdentifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsReferenceIdentifier, f: &mut JsFormatter) -> FormatResult<()> { let JsReferenceIdentifierFields { value_token } = node.as_fields(); - formatted![formatter, [value_token.format()]] + write![f, [value_token.format()]] } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/script.rs b/crates/rome_js_formatter/src/js/auxiliary/script.rs index 43e65195a65..c0d22dc2012 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/script.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/script.rs @@ -1,12 +1,13 @@ use crate::prelude::*; -use crate::utils::format_interpreter; +use crate::utils::FormatInterpreterToken; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsScript; use rome_js_syntax::JsScriptFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsScript, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &JsScript, f: &mut JsFormatter) -> FormatResult<()> { let JsScriptFields { interpreter_token, directives, @@ -14,13 +15,19 @@ impl FormatNodeFields for FormatNodeRule { eof_token, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ - format_interpreter(interpreter_token, formatter)?, + FormatInterpreterToken::new(interpreter_token.as_ref()), directives.format(), - formatter.format_list(&statements), - formatter.format_replaced(&eof_token?, empty_element()), + ] + ]?; + + write![ + f, + [ + statements.format(), + format_replaced(&eof_token?, &empty_element()), hard_line_break() ] ] diff --git a/crates/rome_js_formatter/src/js/auxiliary/spread.rs b/crates/rome_js_formatter/src/js/auxiliary/spread.rs index fcb2654747f..ec07631d2f3 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/spread.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/spread.rs @@ -1,16 +1,16 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsSpread; use rome_js_syntax::JsSpreadFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsSpread, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &JsSpread, f: &mut JsFormatter) -> FormatResult<()> { let JsSpreadFields { dotdotdot_token, argument, } = node.as_fields(); - formatted![formatter, [dotdotdot_token.format(), argument.format()]] + write![f, [dotdotdot_token.format(), argument.format()]] } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/static_modifier.rs b/crates/rome_js_formatter/src/js/auxiliary/static_modifier.rs index dfe577a78fc..af3db1badba 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/static_modifier.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/static_modifier.rs @@ -1,16 +1,14 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsStaticModifier; use rome_js_syntax::JsStaticModifierFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsStaticModifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsStaticModifier, f: &mut JsFormatter) -> FormatResult<()> { let JsStaticModifierFields { modifier_token } = node.as_fields(); - formatted![formatter, [modifier_token.format()]] + write![f, [modifier_token.format()]] } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/variable_declaration_clause.rs b/crates/rome_js_formatter/src/js/auxiliary/variable_declaration_clause.rs index f00899cc763..6784dbf2980 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/variable_declaration_clause.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/variable_declaration_clause.rs @@ -1,24 +1,16 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; - +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; use rome_js_syntax::JsVariableDeclarationClause; use rome_js_syntax::JsVariableDeclarationClauseFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsVariableDeclarationClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsVariableDeclarationClause, f: &mut JsFormatter) -> FormatResult<()> { let JsVariableDeclarationClauseFields { declaration, semicolon_token, } = node.as_fields(); - format_with_semicolon( - formatter, - formatted![formatter, [declaration.format()]]?, - semicolon_token, - ) + FormatWithSemicolon::new(&declaration.format(), semicolon_token.as_ref()).fmt(f) } } diff --git a/crates/rome_js_formatter/src/js/auxiliary/variable_declarator.rs b/crates/rome_js_formatter/src/js/auxiliary/variable_declarator.rs index 4b953ca152c..344e8151464 100644 --- a/crates/rome_js_formatter/src/js/auxiliary/variable_declarator.rs +++ b/crates/rome_js_formatter/src/js/auxiliary/variable_declarator.rs @@ -1,26 +1,25 @@ use crate::prelude::*; -use crate::utils::format_initializer_clause; - +use crate::utils::FormatInitializerClause; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsVariableDeclarator; use rome_js_syntax::JsVariableDeclaratorFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsVariableDeclarator, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsVariableDeclarator, f: &mut JsFormatter) -> FormatResult<()> { let JsVariableDeclaratorFields { id, variable_annotation, initializer, } = node.as_fields(); - let initializer = format_initializer_clause(formatter, initializer)?; - - formatted![ - formatter, - [id.format(), variable_annotation.format(), initializer] + write![ + f, + [ + id.format(), + variable_annotation.format(), + FormatInitializerClause::new(initializer.as_ref()) + ] ] } } diff --git a/crates/rome_js_formatter/src/js/bindings/array_binding_pattern.rs b/crates/rome_js_formatter/src/js/bindings/array_binding_pattern.rs index b7fb5c10748..635bf76f45f 100644 --- a/crates/rome_js_formatter/src/js/bindings/array_binding_pattern.rs +++ b/crates/rome_js_formatter/src/js/bindings/array_binding_pattern.rs @@ -1,27 +1,23 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsArrayBindingPattern; use rome_js_syntax::JsArrayBindingPatternFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsArrayBindingPattern, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsArrayBindingPattern, f: &mut JsFormatter) -> FormatResult<()> { let JsArrayBindingPatternFields { l_brack_token, elements, r_brack_token, } = node.as_fields(); - formatter - .delimited( - &l_brack_token?, - formatted![formatter, [elements.format()]]?, - &r_brack_token?, - ) - .soft_block_indent() - .finish() + write!( + f, + [ + format_delimited(&l_brack_token?, &elements.format(), &r_brack_token?,) + .soft_block_indent() + ] + ) } } diff --git a/crates/rome_js_formatter/src/js/bindings/array_binding_pattern_rest_element.rs b/crates/rome_js_formatter/src/js/bindings/array_binding_pattern_rest_element.rs index 406670b0578..3cd60bc7e90 100644 --- a/crates/rome_js_formatter/src/js/bindings/array_binding_pattern_rest_element.rs +++ b/crates/rome_js_formatter/src/js/bindings/array_binding_pattern_rest_element.rs @@ -1,21 +1,21 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsArrayBindingPatternRestElement; use rome_js_syntax::JsArrayBindingPatternRestElementFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( + fn fmt_fields( node: &JsArrayBindingPatternRestElement, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut JsFormatter, + ) -> FormatResult<()> { let JsArrayBindingPatternRestElementFields { dotdotdot_token, pattern, } = node.as_fields(); - formatted![formatter, [dotdotdot_token.format(), pattern.format(),]] + write![f, [dotdotdot_token.format(), pattern.format()]] } } diff --git a/crates/rome_js_formatter/src/js/bindings/binding_pattern_with_default.rs b/crates/rome_js_formatter/src/js/bindings/binding_pattern_with_default.rs index d5690d111d6..33a47a58609 100644 --- a/crates/rome_js_formatter/src/js/bindings/binding_pattern_with_default.rs +++ b/crates/rome_js_formatter/src/js/bindings/binding_pattern_with_default.rs @@ -1,22 +1,19 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsBindingPatternWithDefault; use rome_js_syntax::JsBindingPatternWithDefaultFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsBindingPatternWithDefault, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsBindingPatternWithDefault, f: &mut JsFormatter) -> FormatResult<()> { let JsBindingPatternWithDefaultFields { pattern, eq_token, default, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ pattern.format(), space_token(), diff --git a/crates/rome_js_formatter/src/js/bindings/constructor_parameters.rs b/crates/rome_js_formatter/src/js/bindings/constructor_parameters.rs index 8a196ba135f..a0698d731d9 100644 --- a/crates/rome_js_formatter/src/js/bindings/constructor_parameters.rs +++ b/crates/rome_js_formatter/src/js/bindings/constructor_parameters.rs @@ -1,27 +1,23 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsConstructorParameters; use rome_js_syntax::JsConstructorParametersFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsConstructorParameters, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsConstructorParameters, f: &mut JsFormatter) -> FormatResult<()> { let JsConstructorParametersFields { l_paren_token, parameters, r_paren_token, } = node.as_fields(); - formatter - .delimited( - &l_paren_token?, - formatted![formatter, [parameters.format()]]?, - &r_paren_token?, - ) - .soft_block_indent() - .finish() + write!( + f, + [ + format_delimited(&l_paren_token?, ¶meters.format(), &r_paren_token?,) + .soft_block_indent() + ] + ) } } diff --git a/crates/rome_js_formatter/src/js/bindings/formal_parameter.rs b/crates/rome_js_formatter/src/js/bindings/formal_parameter.rs index 17661e08cfe..d3035a72bf7 100644 --- a/crates/rome_js_formatter/src/js/bindings/formal_parameter.rs +++ b/crates/rome_js_formatter/src/js/bindings/formal_parameter.rs @@ -1,15 +1,13 @@ use crate::prelude::*; -use crate::utils::format_initializer_clause; +use rome_formatter::write; +use crate::utils::FormatInitializerClause; use crate::FormatNodeFields; use rome_js_syntax::JsFormalParameter; use rome_js_syntax::JsFormalParameterFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsFormalParameter, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsFormalParameter, f: &mut JsFormatter) -> FormatResult<()> { let JsFormalParameterFields { binding, question_mark_token, @@ -17,15 +15,13 @@ impl FormatNodeFields for FormatNodeRule { initializer, } = node.as_fields(); - let initializer = format_initializer_clause(formatter, initializer)?; - - formatted![ - formatter, + write![ + f, [ binding.format(), question_mark_token.format(), type_annotation.format(), - initializer + FormatInitializerClause::new(initializer.as_ref()) ] ] } diff --git a/crates/rome_js_formatter/src/js/bindings/identifier_binding.rs b/crates/rome_js_formatter/src/js/bindings/identifier_binding.rs index 567e88f5efb..5c020478d2c 100644 --- a/crates/rome_js_formatter/src/js/bindings/identifier_binding.rs +++ b/crates/rome_js_formatter/src/js/bindings/identifier_binding.rs @@ -1,16 +1,13 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsIdentifierBinding; use rome_js_syntax::JsIdentifierBindingFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsIdentifierBinding, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsIdentifierBinding, f: &mut JsFormatter) -> FormatResult<()> { let JsIdentifierBindingFields { name_token } = node.as_fields(); - formatted![formatter, [name_token.format()]] + write![f, [name_token.format()]] } } diff --git a/crates/rome_js_formatter/src/js/bindings/object_binding_pattern.rs b/crates/rome_js_formatter/src/js/bindings/object_binding_pattern.rs index b9f9709c3f6..a5d1e59aca2 100644 --- a/crates/rome_js_formatter/src/js/bindings/object_binding_pattern.rs +++ b/crates/rome_js_formatter/src/js/bindings/object_binding_pattern.rs @@ -1,27 +1,23 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsObjectBindingPattern; use rome_js_syntax::JsObjectBindingPatternFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsObjectBindingPattern, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsObjectBindingPattern, f: &mut JsFormatter) -> FormatResult<()> { let JsObjectBindingPatternFields { l_curly_token, properties, r_curly_token, } = node.as_fields(); - formatter - .delimited( - &l_curly_token?, - formatted![formatter, [properties.format()]]?, - &r_curly_token?, - ) - .soft_block_spaces() - .finish() + write!( + f, + [ + format_delimited(&l_curly_token?, &properties.format(), &r_curly_token?,) + .soft_block_spaces() + ] + ) } } diff --git a/crates/rome_js_formatter/src/js/bindings/object_binding_pattern_property.rs b/crates/rome_js_formatter/src/js/bindings/object_binding_pattern_property.rs index 54be4e7c6f9..f8225385ed9 100644 --- a/crates/rome_js_formatter/src/js/bindings/object_binding_pattern_property.rs +++ b/crates/rome_js_formatter/src/js/bindings/object_binding_pattern_property.rs @@ -1,16 +1,14 @@ use crate::prelude::*; use crate::utils::FormatMemberName; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsObjectBindingPatternProperty; use rome_js_syntax::JsObjectBindingPatternPropertyFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsObjectBindingPatternProperty, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsObjectBindingPatternProperty, f: &mut JsFormatter) -> FormatResult<()> { let JsObjectBindingPatternPropertyFields { member, colon_token, @@ -18,16 +16,20 @@ impl FormatNodeFields init, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ FormatMemberName::from(member?), colon_token.format(), space_token(), pattern.format(), - init.format() - .with_or_empty(|node| formatted![formatter, [space_token(), node]]), ] - ] + ]?; + + if let Some(init) = init { + write!(f, [space_token(), init.format()])?; + } + + Ok(()) } } diff --git a/crates/rome_js_formatter/src/js/bindings/object_binding_pattern_rest.rs b/crates/rome_js_formatter/src/js/bindings/object_binding_pattern_rest.rs index f81b8f4706f..4520866c784 100644 --- a/crates/rome_js_formatter/src/js/bindings/object_binding_pattern_rest.rs +++ b/crates/rome_js_formatter/src/js/bindings/object_binding_pattern_rest.rs @@ -1,19 +1,16 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsObjectBindingPatternRest; use rome_js_syntax::JsObjectBindingPatternRestFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsObjectBindingPatternRest, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsObjectBindingPatternRest, f: &mut JsFormatter) -> FormatResult<()> { let JsObjectBindingPatternRestFields { dotdotdot_token, binding, } = node.as_fields(); - formatted![formatter, [dotdotdot_token.format(), binding.format(),]] + write![f, [dotdotdot_token.format(), binding.format(),]] } } diff --git a/crates/rome_js_formatter/src/js/bindings/object_binding_pattern_shorthand_property.rs b/crates/rome_js_formatter/src/js/bindings/object_binding_pattern_shorthand_property.rs index 5e4f560ee60..5162154b3db 100644 --- a/crates/rome_js_formatter/src/js/bindings/object_binding_pattern_shorthand_property.rs +++ b/crates/rome_js_formatter/src/js/bindings/object_binding_pattern_shorthand_property.rs @@ -1,25 +1,24 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsObjectBindingPatternShorthandProperty; use rome_js_syntax::JsObjectBindingPatternShorthandPropertyFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( + fn fmt_fields( node: &JsObjectBindingPatternShorthandProperty, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut JsFormatter, + ) -> FormatResult<()> { let JsObjectBindingPatternShorthandPropertyFields { identifier, init } = node.as_fields(); - formatted![ - formatter, - [ - identifier.format(), - init.format() - .with_or_empty(|node| formatted![formatter, [space_token(), node]]) - ] - ] + write![f, [identifier.format()]]?; + + if let Some(init) = init { + write!(f, [space_token(), init.format()])?; + } + + Ok(()) } } diff --git a/crates/rome_js_formatter/src/js/bindings/parameters.rs b/crates/rome_js_formatter/src/js/bindings/parameters.rs index b57c6368373..debcdaa228e 100644 --- a/crates/rome_js_formatter/src/js/bindings/parameters.rs +++ b/crates/rome_js_formatter/src/js/bindings/parameters.rs @@ -1,24 +1,23 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsParameters; use rome_js_syntax::JsParametersFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsParameters, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &JsParameters, f: &mut JsFormatter) -> FormatResult<()> { let JsParametersFields { l_paren_token, items, r_paren_token, } = node.as_fields(); - formatter - .delimited( - &l_paren_token?, - formatted![formatter, [items.format()]]?, - &r_paren_token?, - ) - .soft_block_indent() - .finish() + write!( + f, + [ + format_delimited(&l_paren_token?, &items.format(), &r_paren_token?,) + .soft_block_indent() + ] + ) } } diff --git a/crates/rome_js_formatter/src/js/bindings/rest_parameter.rs b/crates/rome_js_formatter/src/js/bindings/rest_parameter.rs index 2dfe6062ceb..ba575c7c514 100644 --- a/crates/rome_js_formatter/src/js/bindings/rest_parameter.rs +++ b/crates/rome_js_formatter/src/js/bindings/rest_parameter.rs @@ -1,22 +1,19 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsRestParameter; use rome_js_syntax::JsRestParameterFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsRestParameter, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsRestParameter, f: &mut JsFormatter) -> FormatResult<()> { let JsRestParameterFields { dotdotdot_token, binding, type_annotation, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ dotdotdot_token.format(), binding.format(), diff --git a/crates/rome_js_formatter/src/js/classes/constructor_class_member.rs b/crates/rome_js_formatter/src/js/classes/constructor_class_member.rs index 120f39992e3..008e95807ba 100644 --- a/crates/rome_js_formatter/src/js/classes/constructor_class_member.rs +++ b/crates/rome_js_formatter/src/js/classes/constructor_class_member.rs @@ -1,14 +1,12 @@ use crate::prelude::*; use crate::utils::FormatMemberName; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsConstructorClassMember; use rome_js_syntax::JsConstructorClassMemberFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsConstructorClassMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsConstructorClassMember, f: &mut JsFormatter) -> FormatResult<()> { let JsConstructorClassMemberFields { modifiers, name, @@ -16,8 +14,8 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsEmptyClassMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsEmptyClassMember, f: &mut JsFormatter) -> FormatResult<()> { let JsEmptyClassMemberFields { semicolon_token } = node.as_fields(); - Ok(formatter.format_replaced(&semicolon_token?, empty_element())) + write!(f, [format_replaced(&semicolon_token?, &empty_element())]) } } diff --git a/crates/rome_js_formatter/src/js/classes/extends_clause.rs b/crates/rome_js_formatter/src/js/classes/extends_clause.rs index c8ca92d2d81..0b9fbceec66 100644 --- a/crates/rome_js_formatter/src/js/classes/extends_clause.rs +++ b/crates/rome_js_formatter/src/js/classes/extends_clause.rs @@ -1,28 +1,25 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsExtendsClause; use rome_js_syntax::JsExtendsClauseFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsExtendsClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsExtendsClause, f: &mut JsFormatter) -> FormatResult<()> { let JsExtendsClauseFields { extends_token, super_class, type_arguments, } = node.as_fields(); - Ok(formatted![ - formatter, + write![ + f, [ extends_token.format(), space_token(), super_class.format(), type_arguments.format(), ] - ]?) + ] } } diff --git a/crates/rome_js_formatter/src/js/classes/getter_class_member.rs b/crates/rome_js_formatter/src/js/classes/getter_class_member.rs index 7039ec518a0..e2986bbb0bd 100644 --- a/crates/rome_js_formatter/src/js/classes/getter_class_member.rs +++ b/crates/rome_js_formatter/src/js/classes/getter_class_member.rs @@ -1,14 +1,12 @@ use crate::prelude::*; use crate::utils::FormatMemberName; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsGetterClassMember; use rome_js_syntax::JsGetterClassMemberFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsGetterClassMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsGetterClassMember, f: &mut JsFormatter) -> FormatResult<()> { let JsGetterClassMemberFields { modifiers, get_token, @@ -19,8 +17,8 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsMethodClassMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsMethodClassMember, f: &mut JsFormatter) -> FormatResult<()> { let JsMethodClassMemberFields { modifiers, async_token, @@ -21,14 +19,15 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsPropertyClassMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsPropertyClassMember, f: &mut JsFormatter) -> FormatResult<()> { let JsPropertyClassMemberFields { modifiers, name, @@ -17,21 +16,20 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsSetterClassMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsSetterClassMember, f: &mut JsFormatter) -> FormatResult<()> { let JsSetterClassMemberFields { modifiers, set_token, @@ -19,8 +17,8 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( + fn fmt_fields( node: &JsStaticInitializationBlockClassMember, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut JsFormatter, + ) -> FormatResult<()> { let JsStaticInitializationBlockClassMemberFields { static_token, l_curly_token, @@ -18,15 +18,14 @@ impl FormatNodeFields r_curly_token, } = node.as_fields(); - let static_token = static_token.format(); - let separated = formatter - .delimited( - &l_curly_token?, - formatter.format_list(&statements), - &r_curly_token?, - ) - .block_indent() - .finish()?; - formatted![formatter, [static_token, space_token(), separated]] + write!(f, [static_token.format(), space_token()])?; + + write!( + f, + [ + format_delimited(&l_curly_token?, &statements.format(), &r_curly_token?) + .block_indent() + ] + ) } } diff --git a/crates/rome_js_formatter/src/js/declarations/catch_declaration.rs b/crates/rome_js_formatter/src/js/declarations/catch_declaration.rs index 3ccf37a88ae..6280ddf0051 100644 --- a/crates/rome_js_formatter/src/js/declarations/catch_declaration.rs +++ b/crates/rome_js_formatter/src/js/declarations/catch_declaration.rs @@ -1,14 +1,11 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsCatchDeclaration; use rome_js_syntax::JsCatchDeclarationFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsCatchDeclaration, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsCatchDeclaration, f: &mut JsFormatter) -> FormatResult<()> { let JsCatchDeclarationFields { l_paren_token, binding, @@ -16,13 +13,14 @@ impl FormatNodeFields for FormatNodeRule type_annotation, } = node.as_fields(); - formatter - .delimited( + write!( + f, + [format_delimited( &l_paren_token?, - formatted![formatter, [binding.format(), type_annotation.format()]]?, + &format_args![binding.format(), type_annotation.format()], &r_paren_token?, ) - .soft_block_indent() - .finish() + .soft_block_indent()] + ) } } diff --git a/crates/rome_js_formatter/src/js/declarations/class_declaration.rs b/crates/rome_js_formatter/src/js/declarations/class_declaration.rs index 97ec925eb95..606f8a27e08 100644 --- a/crates/rome_js_formatter/src/js/declarations/class_declaration.rs +++ b/crates/rome_js_formatter/src/js/declarations/class_declaration.rs @@ -1,13 +1,10 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{JsAnyClass, JsClassDeclaration}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsClassDeclaration, - formatter: &JsFormatter, - ) -> FormatResult { - formatted![formatter, [JsAnyClass::from(node.clone()).format()]] + fn fmt_fields(node: &JsClassDeclaration, f: &mut JsFormatter) -> FormatResult<()> { + write![f, [JsAnyClass::from(node.clone()).format()]] } } diff --git a/crates/rome_js_formatter/src/js/declarations/class_export_default_declaration.rs b/crates/rome_js_formatter/src/js/declarations/class_export_default_declaration.rs index a0b3a723edc..d19ac851e44 100644 --- a/crates/rome_js_formatter/src/js/declarations/class_export_default_declaration.rs +++ b/crates/rome_js_formatter/src/js/declarations/class_export_default_declaration.rs @@ -1,16 +1,13 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsAnyClass; use rome_js_syntax::JsClassExportDefaultDeclaration; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsClassExportDefaultDeclaration, - formatter: &JsFormatter, - ) -> FormatResult { - formatted![formatter, [JsAnyClass::from(node.clone()).format()]] + fn fmt_fields(node: &JsClassExportDefaultDeclaration, f: &mut JsFormatter) -> FormatResult<()> { + write![f, [JsAnyClass::from(node.clone()).format()]] } } diff --git a/crates/rome_js_formatter/src/js/declarations/for_variable_declaration.rs b/crates/rome_js_formatter/src/js/declarations/for_variable_declaration.rs index bf346641a17..703bfd903fd 100644 --- a/crates/rome_js_formatter/src/js/declarations/for_variable_declaration.rs +++ b/crates/rome_js_formatter/src/js/declarations/for_variable_declaration.rs @@ -1,21 +1,18 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsForVariableDeclaration; use rome_js_syntax::JsForVariableDeclarationFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsForVariableDeclaration, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsForVariableDeclaration, f: &mut JsFormatter) -> FormatResult<()> { let JsForVariableDeclarationFields { kind_token, declarator, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [kind_token.format(), space_token(), declarator.format(),] ] } diff --git a/crates/rome_js_formatter/src/js/declarations/function_declaration.rs b/crates/rome_js_formatter/src/js/declarations/function_declaration.rs index 3ea96a21d6e..0260cd20d6c 100644 --- a/crates/rome_js_formatter/src/js/declarations/function_declaration.rs +++ b/crates/rome_js_formatter/src/js/declarations/function_declaration.rs @@ -1,13 +1,10 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{JsAnyFunction, JsFunctionDeclaration}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsFunctionDeclaration, - formatter: &JsFormatter, - ) -> FormatResult { - formatted![formatter, [JsAnyFunction::from(node.clone()).format()]] + fn fmt_fields(node: &JsFunctionDeclaration, f: &mut JsFormatter) -> FormatResult<()> { + write![f, [JsAnyFunction::from(node.clone()).format()]] } } diff --git a/crates/rome_js_formatter/src/js/declarations/function_export_default_declaration.rs b/crates/rome_js_formatter/src/js/declarations/function_export_default_declaration.rs index 5bd4c7b9b01..231c8baa6bf 100644 --- a/crates/rome_js_formatter/src/js/declarations/function_export_default_declaration.rs +++ b/crates/rome_js_formatter/src/js/declarations/function_export_default_declaration.rs @@ -1,4 +1,5 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsAnyFunction; @@ -7,10 +8,10 @@ use rome_js_syntax::JsFunctionExportDefaultDeclaration; impl FormatNodeFields for FormatNodeRule { - fn format_fields( + fn fmt_fields( node: &JsFunctionExportDefaultDeclaration, - formatter: &JsFormatter, - ) -> FormatResult { - formatted![formatter, [JsAnyFunction::from(node.clone()).format()]] + f: &mut JsFormatter, + ) -> FormatResult<()> { + write![f, [JsAnyFunction::from(node.clone()).format()]] } } diff --git a/crates/rome_js_formatter/src/js/declarations/variable_declaration.rs b/crates/rome_js_formatter/src/js/declarations/variable_declaration.rs index 583e8987908..a6774ba9c3c 100644 --- a/crates/rome_js_formatter/src/js/declarations/variable_declaration.rs +++ b/crates/rome_js_formatter/src/js/declarations/variable_declaration.rs @@ -1,19 +1,14 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsVariableDeclaration; use rome_js_syntax::JsVariableDeclarationFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsVariableDeclaration, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsVariableDeclaration, f: &mut JsFormatter) -> FormatResult<()> { let JsVariableDeclarationFields { kind, declarators } = node.as_fields(); - formatted![ - formatter, - [kind.format(), space_token(), declarators.format(),] - ] + write![f, [kind.format(), space_token(), declarators.format(),]] } } diff --git a/crates/rome_js_formatter/src/js/expressions/array_expression.rs b/crates/rome_js_formatter/src/js/expressions/array_expression.rs index 2913c0d000c..000db959cc3 100644 --- a/crates/rome_js_formatter/src/js/expressions/array_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/array_expression.rs @@ -1,29 +1,30 @@ -use crate::prelude::*; - use crate::generated::FormatJsArrayElementList; +use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsArrayExpression; use rome_js_syntax::JsArrayExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsArrayExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsArrayExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsArrayExpressionFields { l_brack_token, elements, r_brack_token, } = node.as_fields(); - let group_id = formatter.group_id("array"); + let group_id = f.group_id("array"); - let elements = - FormatJsArrayElementList::format_with_group_id(&elements, formatter, Some(group_id))?; + let elements = format_with(|f| { + FormatJsArrayElementList::format_with_group_id(&elements, f, Some(group_id)) + }); - formatter - .delimited(&l_brack_token?, elements, &r_brack_token?) - .soft_block_indent_with_group_id(Some(group_id)) - .finish() + write!( + f, + [ + format_delimited(&l_brack_token?, &elements, &r_brack_token?) + .soft_block_indent_with_group_id(Some(group_id)) + ] + ) } } diff --git a/crates/rome_js_formatter/src/js/expressions/arrow_function_expression.rs b/crates/rome_js_formatter/src/js/expressions/arrow_function_expression.rs index 563156acb14..4b88f250eed 100644 --- a/crates/rome_js_formatter/src/js/expressions/arrow_function_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/arrow_function_expression.rs @@ -1,13 +1,11 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::{JsAnyFunction, JsArrowFunctionExpression}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsArrowFunctionExpression, - formatter: &JsFormatter, - ) -> FormatResult { - formatted![formatter, [JsAnyFunction::from(node.clone()).format()]] + fn fmt_fields(node: &JsArrowFunctionExpression, f: &mut JsFormatter) -> FormatResult<()> { + write![f, [JsAnyFunction::from(node.clone()).format()]] } } diff --git a/crates/rome_js_formatter/src/js/expressions/assignment_expression.rs b/crates/rome_js_formatter/src/js/expressions/assignment_expression.rs index 764745f85ea..6486f5c8fce 100644 --- a/crates/rome_js_formatter/src/js/expressions/assignment_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/assignment_expression.rs @@ -1,32 +1,26 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsAssignmentExpression; use rome_js_syntax::JsAssignmentExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsAssignmentExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsAssignmentExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsAssignmentExpressionFields { left, operator_token, right, } = node.as_fields(); - Ok(group_elements(formatted![ - formatter, - [ + write!( + f, + [group_elements(&format_args![ left.format(), space_token(), operator_token.format(), line_suffix_boundary(), - group_elements(soft_line_indent_or_space(formatted![ - formatter, - [right.format()] - ]?)), - ] - ]?)) + group_elements(&soft_line_indent_or_space(&right.format())), + ])] + ) } } diff --git a/crates/rome_js_formatter/src/js/expressions/await_expression.rs b/crates/rome_js_formatter/src/js/expressions/await_expression.rs index 27a131d4ccf..aa26229d1f7 100644 --- a/crates/rome_js_formatter/src/js/expressions/await_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/await_expression.rs @@ -1,22 +1,17 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsAwaitExpression; use rome_js_syntax::JsAwaitExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsAwaitExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsAwaitExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsAwaitExpressionFields { await_token, argument, } = node.as_fields(); - formatted![ - formatter, - [await_token.format(), space_token(), argument.format(),] - ] + write![f, [await_token.format(), space_token(), argument.format(),]] } } diff --git a/crates/rome_js_formatter/src/js/expressions/big_int_literal_expression.rs b/crates/rome_js_formatter/src/js/expressions/big_int_literal_expression.rs index f5be76faa45..fbc4b0d6ff6 100644 --- a/crates/rome_js_formatter/src/js/expressions/big_int_literal_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/big_int_literal_expression.rs @@ -1,3 +1,4 @@ +use rome_formatter::write; use std::borrow::Cow; use crate::prelude::*; @@ -8,20 +9,22 @@ use rome_js_syntax::JsBigIntLiteralExpression; use rome_js_syntax::JsBigIntLiteralExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsBigIntLiteralExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsBigIntLiteralExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsBigIntLiteralExpressionFields { value_token } = node.as_fields(); let value_token = value_token?; let original = value_token.text_trimmed(); match original.to_ascii_lowercase_cow() { - Cow::Borrowed(_) => formatted![formatter, [value_token.format()]], - Cow::Owned(lowercase) => Ok(formatter.format_replaced( - &value_token, - Token::new_dynamic(lowercase, value_token.text_trimmed_range().start()).into(), - )), + Cow::Borrowed(_) => write![f, [value_token.format()]], + Cow::Owned(lowercase) => { + write!( + f, + [format_replaced( + &value_token, + &dynamic_token(&lowercase, value_token.text_trimmed_range().start()) + )] + ) + } } } } diff --git a/crates/rome_js_formatter/src/js/expressions/binary_expression.rs b/crates/rome_js_formatter/src/js/expressions/binary_expression.rs index 5047166b85e..4573e892979 100644 --- a/crates/rome_js_formatter/src/js/expressions/binary_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/binary_expression.rs @@ -5,10 +5,7 @@ use crate::FormatNodeFields; use rome_js_syntax::JsBinaryExpression; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsBinaryExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsBinaryExpression, formatter: &mut JsFormatter) -> FormatResult<()> { format_binary_like_expression( JsAnyBinaryLikeExpression::JsBinaryExpression(node.clone()), formatter, diff --git a/crates/rome_js_formatter/src/js/expressions/boolean_literal_expression.rs b/crates/rome_js_formatter/src/js/expressions/boolean_literal_expression.rs index 50eb3c7c6c0..995ceac4579 100644 --- a/crates/rome_js_formatter/src/js/expressions/boolean_literal_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/boolean_literal_expression.rs @@ -1,16 +1,13 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsBooleanLiteralExpression; use rome_js_syntax::JsBooleanLiteralExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsBooleanLiteralExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsBooleanLiteralExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsBooleanLiteralExpressionFields { value_token } = node.as_fields(); - formatted![formatter, [value_token.format()]] + write![f, [value_token.format()]] } } diff --git a/crates/rome_js_formatter/src/js/expressions/call_arguments.rs b/crates/rome_js_formatter/src/js/expressions/call_arguments.rs index f70609e3986..363ae57646c 100644 --- a/crates/rome_js_formatter/src/js/expressions/call_arguments.rs +++ b/crates/rome_js_formatter/src/js/expressions/call_arguments.rs @@ -1,16 +1,13 @@ use crate::prelude::*; use crate::utils::{is_simple_expression, token_has_comments}; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsCallArgumentsFields; use rome_js_syntax::{JsAnyCallArgument, JsCallArguments}; use rome_rowan::{AstSeparatedList, SyntaxResult}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsCallArguments, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsCallArguments, f: &mut JsFormatter) -> FormatResult<()> { let JsCallArgumentsFields { l_paren_token, args, @@ -18,8 +15,8 @@ impl FormatNodeFields for FormatNodeRule { } = node.as_fields(); if is_simple_function_arguments(node)? { - return formatted![ - formatter, + return write![ + f, [ l_paren_token.format(), args.format(), @@ -28,14 +25,13 @@ impl FormatNodeFields for FormatNodeRule { ]; } - formatter - .delimited( - &l_paren_token?, - formatted![formatter, [args.format()]]?, - &r_paren_token?, - ) - .soft_block_indent() - .finish() + write!( + f, + [ + format_delimited(&l_paren_token?, &args.format(), &r_paren_token?,) + .soft_block_indent() + ] + ) } } diff --git a/crates/rome_js_formatter/src/js/expressions/call_expression.rs b/crates/rome_js_formatter/src/js/expressions/call_expression.rs index f24613ca0fc..20d8e7b90ec 100644 --- a/crates/rome_js_formatter/src/js/expressions/call_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/call_expression.rs @@ -6,10 +6,7 @@ use rome_js_syntax::JsCallExpression; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsCallExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsCallExpression, formatter: &mut JsFormatter) -> FormatResult<()> { format_call_expression(node.syntax(), formatter) } } diff --git a/crates/rome_js_formatter/src/js/expressions/class_expression.rs b/crates/rome_js_formatter/src/js/expressions/class_expression.rs index 0a291460a9d..7d2c37132cd 100644 --- a/crates/rome_js_formatter/src/js/expressions/class_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/class_expression.rs @@ -1,13 +1,10 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{JsAnyClass, JsClassExpression}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsClassExpression, - formatter: &JsFormatter, - ) -> FormatResult { - formatted![formatter, [JsAnyClass::from(node.clone()).format()]] + fn fmt_fields(node: &JsClassExpression, f: &mut JsFormatter) -> FormatResult<()> { + write![f, [JsAnyClass::from(node.clone()).format()]] } } diff --git a/crates/rome_js_formatter/src/js/expressions/computed_member_expression.rs b/crates/rome_js_formatter/src/js/expressions/computed_member_expression.rs index 7ce5a17ed1c..a49180fb62c 100644 --- a/crates/rome_js_formatter/src/js/expressions/computed_member_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/computed_member_expression.rs @@ -1,15 +1,12 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsComputedMemberExpression; use rome_js_syntax::JsComputedMemberExpressionFields; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsComputedMemberExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsComputedMemberExpression, f: &mut JsFormatter) -> FormatResult<()> { let mut current = node.clone(); // Find the left most computed expression @@ -28,22 +25,19 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsConditionalExpression, - formatter: &JsFormatter, - ) -> FormatResult { - format_conditional(Conditional::Expression(node.clone()), formatter, false) + fn fmt_fields(node: &JsConditionalExpression, formatter: &mut JsFormatter) -> FormatResult<()> { + format_conditional(&Conditional::Expression(node.clone()), formatter, false) } } diff --git a/crates/rome_js_formatter/src/js/expressions/function_expression.rs b/crates/rome_js_formatter/src/js/expressions/function_expression.rs index 51685894dac..9af451ffcad 100644 --- a/crates/rome_js_formatter/src/js/expressions/function_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/function_expression.rs @@ -1,13 +1,10 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{JsAnyFunction, JsFunctionExpression}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsFunctionExpression, - formatter: &JsFormatter, - ) -> FormatResult { - formatted![formatter, [JsAnyFunction::from(node.clone()).format()]] + fn fmt_fields(node: &JsFunctionExpression, f: &mut JsFormatter) -> FormatResult<()> { + write![f, [JsAnyFunction::from(node.clone()).format()]] } } diff --git a/crates/rome_js_formatter/src/js/expressions/identifier_expression.rs b/crates/rome_js_formatter/src/js/expressions/identifier_expression.rs index 45a77b76bd1..1e4f071002a 100644 --- a/crates/rome_js_formatter/src/js/expressions/identifier_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/identifier_expression.rs @@ -1,16 +1,13 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsIdentifierExpression; use rome_js_syntax::JsIdentifierExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsIdentifierExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsIdentifierExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsIdentifierExpressionFields { name } = node.as_fields(); - formatted![formatter, [name.format()]] + write![f, [name.format()]] } } diff --git a/crates/rome_js_formatter/src/js/expressions/import_call_expression.rs b/crates/rome_js_formatter/src/js/expressions/import_call_expression.rs index 83f5c82c232..e0180804e05 100644 --- a/crates/rome_js_formatter/src/js/expressions/import_call_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/import_call_expression.rs @@ -1,19 +1,16 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsImportCallExpression; use rome_js_syntax::JsImportCallExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsImportCallExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsImportCallExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsImportCallExpressionFields { import_token, arguments, } = node.as_fields(); - formatted![formatter, [import_token.format(), arguments.format(),]] + write![f, [import_token.format(), arguments.format(),]] } } diff --git a/crates/rome_js_formatter/src/js/expressions/in_expression.rs b/crates/rome_js_formatter/src/js/expressions/in_expression.rs index dcf3366311c..ce054590a1f 100644 --- a/crates/rome_js_formatter/src/js/expressions/in_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/in_expression.rs @@ -5,10 +5,7 @@ use crate::FormatNodeFields; use rome_js_syntax::JsInExpression; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsInExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsInExpression, formatter: &mut JsFormatter) -> FormatResult<()> { format_binary_like_expression( JsAnyBinaryLikeExpression::JsInExpression(node.clone()), formatter, diff --git a/crates/rome_js_formatter/src/js/expressions/instanceof_expression.rs b/crates/rome_js_formatter/src/js/expressions/instanceof_expression.rs index 36cfed23263..233fdef199a 100644 --- a/crates/rome_js_formatter/src/js/expressions/instanceof_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/instanceof_expression.rs @@ -5,10 +5,7 @@ use crate::FormatNodeFields; use rome_js_syntax::JsInstanceofExpression; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsInstanceofExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsInstanceofExpression, formatter: &mut JsFormatter) -> FormatResult<()> { format_binary_like_expression( JsAnyBinaryLikeExpression::JsInstanceofExpression(node.clone()), formatter, diff --git a/crates/rome_js_formatter/src/js/expressions/logical_expression.rs b/crates/rome_js_formatter/src/js/expressions/logical_expression.rs index 5943be2bb02..fa071765936 100644 --- a/crates/rome_js_formatter/src/js/expressions/logical_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/logical_expression.rs @@ -5,10 +5,7 @@ use crate::FormatNodeFields; use rome_js_syntax::JsLogicalExpression; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsLogicalExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsLogicalExpression, formatter: &mut JsFormatter) -> FormatResult<()> { format_binary_like_expression( JsAnyBinaryLikeExpression::JsLogicalExpression(node.clone()), formatter, diff --git a/crates/rome_js_formatter/src/js/expressions/new_expression.rs b/crates/rome_js_formatter/src/js/expressions/new_expression.rs index c251a6c5e45..746ea769ab1 100644 --- a/crates/rome_js_formatter/src/js/expressions/new_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/new_expression.rs @@ -1,14 +1,11 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsNewExpression; use rome_js_syntax::JsNewExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsNewExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsNewExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsNewExpressionFields { new_token, callee, @@ -16,17 +13,23 @@ impl FormatNodeFields for FormatNodeRule { arguments, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ new_token.format(), space_token(), callee.format(), type_arguments.format(), - arguments - .format() - .or_format(|| formatted![formatter, [token("("), token(")")]]), ] - ] + ]?; + + match arguments { + Some(arguments) => { + write!(f, [arguments.format()]) + } + None => { + write!(f, [token("()")]) + } + } } } diff --git a/crates/rome_js_formatter/src/js/expressions/null_literal_expression.rs b/crates/rome_js_formatter/src/js/expressions/null_literal_expression.rs index 192499f4ac7..6b678d35c48 100644 --- a/crates/rome_js_formatter/src/js/expressions/null_literal_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/null_literal_expression.rs @@ -1,16 +1,13 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsNullLiteralExpression; use rome_js_syntax::JsNullLiteralExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsNullLiteralExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsNullLiteralExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsNullLiteralExpressionFields { value_token } = node.as_fields(); - formatted![formatter, [value_token.format()]] + write![f, [value_token.format()]] } } diff --git a/crates/rome_js_formatter/src/js/expressions/number_literal_expression.rs b/crates/rome_js_formatter/src/js/expressions/number_literal_expression.rs index 9a74aef9b9d..09b3aa6d262 100644 --- a/crates/rome_js_formatter/src/js/expressions/number_literal_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/number_literal_expression.rs @@ -1,16 +1,13 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsNumberLiteralExpression; use rome_js_syntax::JsNumberLiteralExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsNumberLiteralExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsNumberLiteralExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsNumberLiteralExpressionFields { value_token } = node.as_fields(); - formatted![formatter, [value_token.format()]] + write![f, [value_token.format()]] } } diff --git a/crates/rome_js_formatter/src/js/expressions/object_expression.rs b/crates/rome_js_formatter/src/js/expressions/object_expression.rs index 0912c42f2e1..505973857a0 100644 --- a/crates/rome_js_formatter/src/js/expressions/object_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/object_expression.rs @@ -1,14 +1,12 @@ use crate::prelude::*; use crate::utils::has_leading_newline; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsObjectExpression; use rome_js_syntax::JsObjectExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsObjectExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsObjectExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsObjectExpressionFields { l_curly_token, members, @@ -16,23 +14,31 @@ impl FormatNodeFields for FormatNodeRule } = node.as_fields(); let has_newline = has_leading_newline(members.syntax()); - let members_content = formatted![formatter, [members.format()]]?; if members.is_empty() { - formatter - .delimited(&l_curly_token?, members_content, &r_curly_token?) - .soft_block_indent() - .finish() + write!( + f, + [ + format_delimited(&l_curly_token?, &members.format(), &r_curly_token?) + .soft_block_indent() + ] + ) } else if has_newline { - formatter - .delimited(&l_curly_token?, members_content, &r_curly_token?) - .block_indent() - .finish() + write!( + f, + [ + format_delimited(&l_curly_token?, &members.format(), &r_curly_token?) + .block_indent() + ] + ) } else { - formatter - .delimited(&l_curly_token?, members_content, &r_curly_token?) - .soft_block_spaces() - .finish() + write!( + f, + [ + format_delimited(&l_curly_token?, &members.format(), &r_curly_token?) + .soft_block_spaces() + ] + ) } } } diff --git a/crates/rome_js_formatter/src/js/expressions/parenthesized_expression.rs b/crates/rome_js_formatter/src/js/expressions/parenthesized_expression.rs index 506765220e5..fa4421239ad 100644 --- a/crates/rome_js_formatter/src/js/expressions/parenthesized_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/parenthesized_expression.rs @@ -1,5 +1,6 @@ use crate::prelude::*; use crate::utils::{is_simple_expression, FormatPrecedence}; +use rome_formatter::write; use crate::utils::JsAnyBinaryLikeExpression; use crate::FormatNodeFields; @@ -10,10 +11,7 @@ use rome_js_syntax::{ use rome_rowan::{AstNode, SyntaxResult}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsParenthesizedExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsParenthesizedExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsParenthesizedExpressionFields { l_paren_token, expression, @@ -25,32 +23,29 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsPostUpdateExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsPostUpdateExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsPostUpdateExpressionFields { operand, operator_token, } = node.as_fields(); - formatted![formatter, [operand.format(), operator_token.format(),]] + write![f, [operand.format(), operator_token.format(),]] } } diff --git a/crates/rome_js_formatter/src/js/expressions/pre_update_expression.rs b/crates/rome_js_formatter/src/js/expressions/pre_update_expression.rs index ef0c9924930..21aa201c496 100644 --- a/crates/rome_js_formatter/src/js/expressions/pre_update_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/pre_update_expression.rs @@ -1,19 +1,17 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsPreUpdateExpression; use rome_js_syntax::JsPreUpdateExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsPreUpdateExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsPreUpdateExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsPreUpdateExpressionFields { operator_token, operand, } = node.as_fields(); - formatted![formatter, [operator_token.format(), operand.format(),]] + write![f, [operator_token.format(), operand.format(),]] } } diff --git a/crates/rome_js_formatter/src/js/expressions/regex_literal_expression.rs b/crates/rome_js_formatter/src/js/expressions/regex_literal_expression.rs index 6b9d03c69b9..df38e9b46ef 100644 --- a/crates/rome_js_formatter/src/js/expressions/regex_literal_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/regex_literal_expression.rs @@ -1,15 +1,13 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; -use rome_formatter::Token; + use rome_js_syntax::JsRegexLiteralExpression; use rome_js_syntax::JsRegexLiteralExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsRegexLiteralExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsRegexLiteralExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsRegexLiteralExpressionFields { value_token } = node.as_fields(); let value_token = value_token?; let trimmed_raw_string = value_token.text_trimmed(); @@ -18,8 +16,9 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule(); - let sorted_regex_literal = Token::from_syntax_token_cow_slice( - std::borrow::Cow::Owned(format!( + let sorted_regex_literal = syntax_token_cow_slice( + std::borrow::Cow::Owned(std::format!( "{}{}", &trimmed_raw_string[0..end_slash_pos + 1], sorted_flag_string @@ -37,6 +36,7 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsSequenceExpression, - formatter: &JsFormatter, - ) -> FormatResult { - let mut current = node.clone(); - let parent = current.syntax().parent(); + fn fmt_fields(node: &JsSequenceExpression, f: &mut JsFormatter) -> FormatResult<()> { + let content = format_with(|f| { + let mut current = node.clone(); + let parent = current.syntax().parent(); - let has_already_indentation = parent.map_or(false, |parent| { - // Return statement already does the indentation for us - // Arrow function body can't have a sequence expression unless it's parenthesized, otherwise - // would be a syntax error - if matches!(parent.kind(), JsSyntaxKind::JS_RETURN_STATEMENT) { - true - } else if matches!(parent.kind(), JsSyntaxKind::JS_PARENTHESIZED_EXPRESSION) { - // In case we are inside a sequence expression, we have to go up a level and see the great parent. - // Arrow function body and return statements applying indentation for us, so we signal the - // sequence expression to not add other indentation levels - let great_parent = parent.parent().map(|gp| gp.kind()); + let has_already_indentation = parent.map_or(false, |parent| { + // Return statement already does the indentation for us + // Arrow function body can't have a sequence expression unless it's parenthesized, otherwise + // would be a syntax error + if matches!(parent.kind(), JsSyntaxKind::JS_RETURN_STATEMENT) { + true + } else if matches!(parent.kind(), JsSyntaxKind::JS_PARENTHESIZED_EXPRESSION) { + // In case we are inside a sequence expression, we have to go up a level and see the great parent. + // Arrow function body and return statements applying indentation for us, so we signal the + // sequence expression to not add other indentation levels + let great_parent = parent.parent().map(|gp| gp.kind()); - matches!( - great_parent, - Some( - JsSyntaxKind::JS_ARROW_FUNCTION_EXPRESSION - | JsSyntaxKind::JS_RETURN_STATEMENT - | JsSyntaxKind::JS_PROPERTY_OBJECT_MEMBER + matches!( + great_parent, + Some( + JsSyntaxKind::JS_ARROW_FUNCTION_EXPRESSION + | JsSyntaxKind::JS_RETURN_STATEMENT + | JsSyntaxKind::JS_PROPERTY_OBJECT_MEMBER + ) ) - ) - } else { - false - } - }); - - // Find the left most sequence expression - while let Some(sequence_expression) = - JsSequenceExpression::cast(current.left()?.syntax().clone()) - { - current = sequence_expression; - } - - // Format the left most sequence expression - let JsSequenceExpressionFields { - left, - comma_token, - right, - } = current.as_fields(); + } else { + false + } + }); - let mut formatted = ConcatBuilder::default(); - - formatted.entry(formatted![ - formatter, - [left.format()?, comma_token.format()?] - ]?); - - let mut previous_right = right; + // Find the left most sequence expression + while let Some(sequence_expression) = + JsSequenceExpression::cast(current.left()?.syntax().clone()) + { + current = sequence_expression; + } - // Traverse upwards again and concatenate the sequence expression until we find the first non-sequence expression - while let Some(parent_sequence) = current - .syntax() - .parent() - .and_then(JsSequenceExpression::cast) - { + // Format the left most sequence expression let JsSequenceExpressionFields { - left: _left, + left, comma_token, right, - } = parent_sequence.as_fields(); + } = current.as_fields(); - if has_already_indentation { - formatted.entry(formatted![ - formatter, - [ - soft_line_break_or_space(), - previous_right.format()?, - comma_token.format()?, - ] - ]?); - } else { - formatted.entry(formatted![ - formatter, - [indent(formatted![ - formatter, + write![f, [left.format()?, comma_token.format()?]]?; + + let mut previous_right = right; + + // Traverse upwards again and concatenate the sequence expression until we find the first non-sequence expression + while let Some(parent_sequence) = current + .syntax() + .parent() + .and_then(JsSequenceExpression::cast) + { + let JsSequenceExpressionFields { + left: _left, + comma_token, + right, + } = parent_sequence.as_fields(); + + if has_already_indentation { + write![ + f, [ soft_line_break_or_space(), previous_right.format()?, comma_token.format()?, ] - ]?),] - ]?) + ]?; + } else { + write![ + f, + [indent(&format_args![ + soft_line_break_or_space(), + previous_right.format()?, + comma_token.format()?, + ])] + ]?; + } + previous_right = right; + current = parent_sequence; } - previous_right = right; - current = parent_sequence; - } - if has_already_indentation { - formatted.entry(formatted![ - formatter, - [soft_line_break_or_space(), previous_right.format()?,] - ]?); - } else { - formatted.entry(formatted![ - formatter, - [indent(formatted![ - formatter, - [soft_line_break_or_space(), previous_right.format()?,] - ]?),] - ]?) - } + if has_already_indentation { + write![f, [soft_line_break_or_space(), previous_right.format()?,]]?; + } else { + write![ + f, + [indent(&format_args![ + soft_line_break_or_space(), + previous_right.format(), + ])] + ]?; + } + + Ok(()) + }); - Ok(group_elements(formatted.finish())) + write!(f, [group_elements(&content)]) } } diff --git a/crates/rome_js_formatter/src/js/expressions/static_member_expression.rs b/crates/rome_js_formatter/src/js/expressions/static_member_expression.rs index 53d4e93969e..79fd29364fd 100644 --- a/crates/rome_js_formatter/src/js/expressions/static_member_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/static_member_expression.rs @@ -1,6 +1,6 @@ use crate::prelude::*; use crate::FormatNodeFields; -use rome_formatter::ConcatBuilder; +use rome_formatter::{format_args, write, VecBuffer}; use rome_js_syntax::{ JsAnyExpression, JsAnyLiteralExpression, JsAnyName, JsStaticMemberExpression, JsStaticMemberExpressionFields, JsSyntaxNode, JsSyntaxToken, @@ -9,10 +9,7 @@ use rome_rowan::AstNode; use std::ops::Deref; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsStaticMemberExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsStaticMemberExpression, f: &mut JsFormatter) -> FormatResult<()> { let mut current = node.clone(); while let Some(static_member_expression) = @@ -27,91 +24,100 @@ impl FormatNodeFields for FormatNodeRule { - JsAnyName(JsAnyName, &'t JsSyntaxToken), - JsAnyExpression(JsAnyExpression, &'t JsSyntaxToken), + JsAnyName { + name: JsAnyName, + operator: &'t JsSyntaxToken, + }, + JsAnyExpression { + expression: JsAnyExpression, + operator: &'t JsSyntaxToken, + }, } impl<'t> FormatMemberStaticExpression<'t> { fn from_expression(node: JsAnyExpression, operator: &'t JsSyntaxToken) -> Self { - Self::JsAnyExpression(node, operator) + Self::JsAnyExpression { + expression: node, + operator, + } } fn from_name(node: JsAnyName, operator: &'t JsSyntaxToken) -> Self { - Self::JsAnyName(node, operator) + Self::JsAnyName { + name: node, + operator, + } } fn is_number_literal_expression(&self) -> bool { matches!( self, - FormatMemberStaticExpression::JsAnyExpression( - JsAnyExpression::JsAnyLiteralExpression( + FormatMemberStaticExpression::JsAnyExpression { + expression: JsAnyExpression::JsAnyLiteralExpression( JsAnyLiteralExpression::JsNumberLiteralExpression(_) ), .. - ) + } ) } fn syntax(&self) -> &JsSyntaxNode { match self { - FormatMemberStaticExpression::JsAnyName(node, _) => node.syntax(), - FormatMemberStaticExpression::JsAnyExpression(node, _) => node.syntax(), + FormatMemberStaticExpression::JsAnyName { name, .. } => name.syntax(), + FormatMemberStaticExpression::JsAnyExpression { expression, .. } => expression.syntax(), } } fn operator(&self) -> &JsSyntaxToken { match self { - FormatMemberStaticExpression::JsAnyName(_, operator) => operator, - FormatMemberStaticExpression::JsAnyExpression(_, operator) => operator, + FormatMemberStaticExpression::JsAnyName { operator, .. } => operator, + FormatMemberStaticExpression::JsAnyExpression { operator, .. } => operator, } } } -impl<'t> Deref for FormatMemberStaticExpression<'t> { +impl Deref for FormatMemberStaticExpression<'_> { type Target = JsSyntaxNode; fn deref(&self) -> &Self::Target { @@ -119,12 +125,8 @@ impl<'t> Deref for FormatMemberStaticExpression<'t> { } } -impl<'t> Format for FormatMemberStaticExpression<'t> { - type Context = JsFormatContext; - - fn format(&self, formatter: &JsFormatter) -> FormatResult { - let formatted_member = formatted![formatter, [self.syntax().format()]]?; - +impl Format for FormatMemberStaticExpression<'_> { + fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> { let is_member_number_literal = self.is_number_literal_expression(); let object_has_trailing_trivia = self @@ -133,21 +135,34 @@ impl<'t> Format for FormatMemberStaticExpression<'t> { let operator_has_leading_trivia = self.operator().leading_trivia().pieces().len() > 0; + let format_node = format_with(|f| match self { + FormatMemberStaticExpression::JsAnyName { name, .. } => { + write!(f, [name.format()]) + } + FormatMemberStaticExpression::JsAnyExpression { expression, .. } => { + write!(f, [expression.format()]) + } + }); + if is_member_number_literal && (object_has_trailing_trivia || operator_has_leading_trivia) { + let mut buffer = VecBuffer::new(f.state_mut()); + write!(buffer, [format_node])?; + let formatted_member = buffer.into_element(); + let (object_leading, object_content, object_trailing) = formatted_member.split_trivia(); - Ok(formatted![ - formatter, - [ - object_leading, - token("("), - object_content, - token(")"), - object_trailing, - ] - ]?) + write!( + f, + [format_once(|f| { + f.write_element(object_leading)?; + write!(f, [token("(")])?; + f.write_element(object_content)?; + write!(f, [token(")")])?; + f.write_element(object_trailing) + })] + ) } else { - Ok(formatted_member) + write!(f, [format_node]) } } } diff --git a/crates/rome_js_formatter/src/js/expressions/string_literal_expression.rs b/crates/rome_js_formatter/src/js/expressions/string_literal_expression.rs index 38b1c827f32..39634a97153 100644 --- a/crates/rome_js_formatter/src/js/expressions/string_literal_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/string_literal_expression.rs @@ -1,4 +1,6 @@ use crate::prelude::*; +use rome_formatter::{write, Buffer, VecBuffer}; + use crate::utils::{FormatLiteralStringToken, StringLiteralParentKind}; use crate::FormatNodeFields; use rome_js_syntax::JsExpressionStatement; @@ -7,10 +9,7 @@ use rome_js_syntax::JsStringLiteralExpressionFields; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsStringLiteralExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsStringLiteralExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsStringLiteralExpressionFields { value_token } = node.as_fields(); let value_token = value_token?; @@ -19,18 +18,38 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsSuperExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsSuperExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsSuperExpressionFields { super_token } = node.as_fields(); - formatted![formatter, [super_token.format()]] + write![f, [super_token.format()]] } } diff --git a/crates/rome_js_formatter/src/js/expressions/template.rs b/crates/rome_js_formatter/src/js/expressions/template.rs index f3b7c38a811..d9a8cd803a4 100644 --- a/crates/rome_js_formatter/src/js/expressions/template.rs +++ b/crates/rome_js_formatter/src/js/expressions/template.rs @@ -1,11 +1,12 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsTemplate; use rome_js_syntax::JsTemplateFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsTemplate, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &JsTemplate, f: &mut JsFormatter) -> FormatResult<()> { let JsTemplateFields { tag, type_arguments, @@ -14,18 +15,15 @@ impl FormatNodeFields for FormatNodeRule { r_tick_token, } = node.as_fields(); - let l_tick = l_tick_token.format(); - let r_tick = r_tick_token.format(); - - formatted![ - formatter, + write![ + f, [ tag.format(), type_arguments.format(), line_suffix_boundary(), - l_tick, - concat_elements(formatter.format_all(elements.iter().formatted())?), - r_tick + l_tick_token.format(), + elements.format(), + r_tick_token.format() ] ] } diff --git a/crates/rome_js_formatter/src/js/expressions/template_chunk_element.rs b/crates/rome_js_formatter/src/js/expressions/template_chunk_element.rs index 767efe1ff6a..776dcd75965 100644 --- a/crates/rome_js_formatter/src/js/expressions/template_chunk_element.rs +++ b/crates/rome_js_formatter/src/js/expressions/template_chunk_element.rs @@ -5,10 +5,7 @@ use crate::FormatNodeFields; use rome_js_syntax::{JsTemplateChunkElement, JsTemplateChunkElementFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsTemplateChunkElement, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsTemplateChunkElement, formatter: &mut JsFormatter) -> FormatResult<()> { let JsTemplateChunkElementFields { template_chunk_token, } = node.as_fields(); diff --git a/crates/rome_js_formatter/src/js/expressions/template_element.rs b/crates/rome_js_formatter/src/js/expressions/template_element.rs index bac57111d59..680dc15ddb9 100644 --- a/crates/rome_js_formatter/src/js/expressions/template_element.rs +++ b/crates/rome_js_formatter/src/js/expressions/template_element.rs @@ -4,10 +4,7 @@ use crate::FormatNodeFields; use rome_js_syntax::JsTemplateElement; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsTemplateElement, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsTemplateElement, formatter: &mut JsFormatter) -> FormatResult<()> { format_template_literal(TemplateElement::Js(node.clone()), formatter) } } diff --git a/crates/rome_js_formatter/src/js/expressions/this_expression.rs b/crates/rome_js_formatter/src/js/expressions/this_expression.rs index d29a1015346..64ee57ba777 100644 --- a/crates/rome_js_formatter/src/js/expressions/this_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/this_expression.rs @@ -1,16 +1,14 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsThisExpression; use rome_js_syntax::JsThisExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsThisExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsThisExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsThisExpressionFields { this_token } = node.as_fields(); - formatted![formatter, [this_token.format()]] + write![f, [this_token.format()]] } } diff --git a/crates/rome_js_formatter/src/js/expressions/unary_expression.rs b/crates/rome_js_formatter/src/js/expressions/unary_expression.rs index 97a08554db3..8bd174bd265 100644 --- a/crates/rome_js_formatter/src/js/expressions/unary_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/unary_expression.rs @@ -1,5 +1,6 @@ use crate::prelude::*; use crate::utils::is_simple_expression; +use rome_formatter::{format_args, write}; use crate::FormatNodeFields; use rome_js_syntax::JsPreUpdateOperator; @@ -7,10 +8,7 @@ use rome_js_syntax::{JsAnyExpression, JsUnaryExpression}; use rome_js_syntax::{JsUnaryExpressionFields, JsUnaryOperator}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsUnaryExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsUnaryExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsUnaryExpressionFields { operator_token, argument, @@ -27,8 +25,8 @@ impl FormatNodeFields for FormatNodeRule { ); if is_keyword_operator { - return formatted![ - formatter, + return write![ + f, [operator_token.format(), space_token(), argument.format(),] ]; } @@ -56,9 +54,9 @@ impl FormatNodeFields for FormatNodeRule { }; if is_ambiguous_expression { - let parenthesized = if is_simple_expression(&argument)? { - formatted![ - formatter, + if is_simple_expression(&argument)? { + write![ + f, [ operator_token.format(), token("("), @@ -67,25 +65,20 @@ impl FormatNodeFields for FormatNodeRule { ] ] } else { - formatted![ - formatter, + write![ + f, [ operator_token.format(), - group_elements(formatted![ - formatter, - [ - token("("), - soft_block_indent(formatted![formatter, [argument.format()]]?), - token(")"), - ] - ]?), + group_elements(&format_args![ + token("("), + soft_block_indent(&argument.format()), + token(")"), + ]), ] ] - }; - - return parenthesized; + } + } else { + write![f, [operator_token.format(), argument.format(),]] } - - formatted![formatter, [operator_token.format(), argument.format(),]] } } diff --git a/crates/rome_js_formatter/src/js/expressions/yield_argument.rs b/crates/rome_js_formatter/src/js/expressions/yield_argument.rs index c6c5c9105ab..db1c732419c 100644 --- a/crates/rome_js_formatter/src/js/expressions/yield_argument.rs +++ b/crates/rome_js_formatter/src/js/expressions/yield_argument.rs @@ -1,22 +1,17 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsYieldArgument; use rome_js_syntax::JsYieldArgumentFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsYieldArgument, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsYieldArgument, f: &mut JsFormatter) -> FormatResult<()> { let JsYieldArgumentFields { star_token, expression, } = node.as_fields(); - formatted![ - formatter, - [star_token.format(), space_token(), expression.format()] - ] + write![f, [star_token.format(), space_token(), expression.format()]] } } diff --git a/crates/rome_js_formatter/src/js/expressions/yield_expression.rs b/crates/rome_js_formatter/src/js/expressions/yield_expression.rs index e663e8f5c1b..3f45cb5c6cb 100644 --- a/crates/rome_js_formatter/src/js/expressions/yield_expression.rs +++ b/crates/rome_js_formatter/src/js/expressions/yield_expression.rs @@ -1,19 +1,17 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsYieldExpression; use rome_js_syntax::JsYieldExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsYieldExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsYieldExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsYieldExpressionFields { yield_token, argument, } = node.as_fields(); - formatted![formatter, [yield_token.format(), argument.format()]] + write![f, [yield_token.format(), argument.format()]] } } diff --git a/crates/rome_js_formatter/src/js/lists/array_assignment_pattern_element_list.rs b/crates/rome_js_formatter/src/js/lists/array_assignment_pattern_element_list.rs index 77ac9baff06..24840a57d94 100644 --- a/crates/rome_js_formatter/src/js/lists/array_assignment_pattern_element_list.rs +++ b/crates/rome_js_formatter/src/js/lists/array_assignment_pattern_element_list.rs @@ -1,15 +1,15 @@ use crate::generated::FormatJsArrayAssignmentPatternElementList; use crate::prelude::*; -use crate::utils::array::format_array_node; +use crate::utils::array::write_array_node; use rome_js_syntax::JsArrayAssignmentPatternElementList; impl FormatRule for FormatJsArrayAssignmentPatternElementList { type Context = JsFormatContext; - fn format( + fn fmt( node: &JsArrayAssignmentPatternElementList, - formatter: &JsFormatter, - ) -> FormatResult { - format_array_node(node, formatter) + formatter: &mut JsFormatter, + ) -> FormatResult<()> { + write_array_node(node, formatter) } } diff --git a/crates/rome_js_formatter/src/js/lists/array_binding_pattern_element_list.rs b/crates/rome_js_formatter/src/js/lists/array_binding_pattern_element_list.rs index f533ff41f24..390f4e06393 100644 --- a/crates/rome_js_formatter/src/js/lists/array_binding_pattern_element_list.rs +++ b/crates/rome_js_formatter/src/js/lists/array_binding_pattern_element_list.rs @@ -1,15 +1,15 @@ use crate::generated::FormatJsArrayBindingPatternElementList; use crate::prelude::*; -use crate::utils::array::format_array_node; +use crate::utils::array::write_array_node; use rome_js_syntax::JsArrayBindingPatternElementList; impl FormatRule for FormatJsArrayBindingPatternElementList { type Context = JsFormatContext; - fn format( + fn fmt( node: &JsArrayBindingPatternElementList, - formatter: &JsFormatter, - ) -> FormatResult { - format_array_node(node, formatter) + formatter: &mut JsFormatter, + ) -> FormatResult<()> { + write_array_node(node, formatter) } } diff --git a/crates/rome_js_formatter/src/js/lists/array_element_list.rs b/crates/rome_js_formatter/src/js/lists/array_element_list.rs index 9a08f4a0dfc..dfd27189327 100644 --- a/crates/rome_js_formatter/src/js/lists/array_element_list.rs +++ b/crates/rome_js_formatter/src/js/lists/array_element_list.rs @@ -2,8 +2,7 @@ use crate::prelude::*; use rome_formatter::GroupId; use std::convert::Infallible; -use crate::formatter::FormatSeparatedOptions; -use crate::utils::array::format_array_node; +use crate::utils::array::write_array_node; use crate::generated::FormatJsArrayElementList; use crate::utils::has_formatter_trivia; @@ -13,7 +12,7 @@ use rome_rowan::{AstNode, AstSeparatedList}; impl FormatRule for FormatJsArrayElementList { type Context = JsFormatContext; - fn format(node: &JsArrayElementList, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsArrayElementList, formatter: &mut JsFormatter) -> FormatResult<()> { Self::format_with_group_id(node, formatter, None) } } @@ -22,22 +21,21 @@ impl FormatJsArrayElementList { /// Formats the array list with pub fn format_with_group_id( node: &JsArrayElementList, - formatter: &JsFormatter, + f: &mut JsFormatter, group_id: Option, - ) -> FormatResult { + ) -> FormatResult<()> { if !has_formatter_trivia(node.syntax()) && can_print_fill(node) { - return Ok(fill_elements( - soft_line_break_or_space(), - // Using format_separated is valid in this case as can_print_fill does not allow holes - formatter.format_separated_with_options( - node, - || token(","), - FormatSeparatedOptions::default().with_group_id(group_id), - )?, - )); + // Using format_separated is valid in this case as can_print_fill does not allow holes + return f + .fill(soft_line_break_or_space()) + .entries( + node.format_separated(token(",")) + .with_options(FormatSeparatedOptions::default().with_group_id(group_id)), + ) + .finish(); } - format_array_node(node, formatter) + write_array_node(node, f) } } diff --git a/crates/rome_js_formatter/src/js/lists/call_argument_list.rs b/crates/rome_js_formatter/src/js/lists/call_argument_list.rs index 7aaf528c435..cade7805df6 100644 --- a/crates/rome_js_formatter/src/js/lists/call_argument_list.rs +++ b/crates/rome_js_formatter/src/js/lists/call_argument_list.rs @@ -5,10 +5,9 @@ use rome_js_syntax::JsCallArgumentList; impl FormatRule for FormatJsCallArgumentList { type Context = JsFormatContext; - fn format(node: &JsCallArgumentList, formatter: &JsFormatter) -> FormatResult { - Ok(join_elements( - soft_line_break_or_space(), - formatter.format_separated(node, || token(","))?, - )) + fn fmt(node: &JsCallArgumentList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&soft_line_break_or_space()) + .entries(node.format_separated(token(","))) + .finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/class_member_list.rs b/crates/rome_js_formatter/src/js/lists/class_member_list.rs index c433040dc4c..e6a4e3141fc 100644 --- a/crates/rome_js_formatter/src/js/lists/class_member_list.rs +++ b/crates/rome_js_formatter/src/js/lists/class_member_list.rs @@ -5,7 +5,13 @@ use rome_js_syntax::JsClassMemberList; impl FormatRule for FormatJsClassMemberList { type Context = JsFormatContext; - fn format(node: &JsClassMemberList, formatter: &JsFormatter) -> FormatResult { - Ok(formatter.format_list(node)) + fn fmt(node: &JsClassMemberList, f: &mut JsFormatter) -> FormatResult<()> { + let mut join = f.join_nodes_with_hardline(); + + for member in node { + join.entry(member.syntax(), &format_or_verbatim(&member)); + } + + join.finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/constructor_modifier_list.rs b/crates/rome_js_formatter/src/js/lists/constructor_modifier_list.rs index cfefd469cc1..c294773a6de 100644 --- a/crates/rome_js_formatter/src/js/lists/constructor_modifier_list.rs +++ b/crates/rome_js_formatter/src/js/lists/constructor_modifier_list.rs @@ -6,13 +6,9 @@ use rome_rowan::AstNodeList; impl FormatRule for FormatJsConstructorModifierList { type Context = JsFormatContext; - fn format( - node: &JsConstructorModifierList, - formatter: &JsFormatter, - ) -> FormatResult { - Ok(join_elements( - space_token(), - formatter.format_all(node.iter().formatted())?, - )) + fn fmt(node: &JsConstructorModifierList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&space_token()) + .entries(node.iter().formatted()) + .finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/constructor_parameter_list.rs b/crates/rome_js_formatter/src/js/lists/constructor_parameter_list.rs index 4e869b103f2..d2d1e699d10 100644 --- a/crates/rome_js_formatter/src/js/lists/constructor_parameter_list.rs +++ b/crates/rome_js_formatter/src/js/lists/constructor_parameter_list.rs @@ -5,13 +5,9 @@ use rome_js_syntax::JsConstructorParameterList; impl FormatRule for FormatJsConstructorParameterList { type Context = JsFormatContext; - fn format( - node: &JsConstructorParameterList, - formatter: &JsFormatter, - ) -> FormatResult { - Ok(join_elements( - soft_line_break_or_space(), - formatter.format_separated(node, || token(","))?, - )) + fn fmt(node: &JsConstructorParameterList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&soft_line_break_or_space()) + .entries(node.format_separated(token(","))) + .finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/directive_list.rs b/crates/rome_js_formatter/src/js/lists/directive_list.rs index 16797ea034e..d5d1968974b 100644 --- a/crates/rome_js_formatter/src/js/lists/directive_list.rs +++ b/crates/rome_js_formatter/src/js/lists/directive_list.rs @@ -1,44 +1,47 @@ use crate::generated::FormatJsDirectiveList; use crate::prelude::*; +use rome_formatter::write; use rome_js_syntax::JsDirectiveList; use rome_rowan::{AstNode, AstNodeList}; impl FormatRule for FormatJsDirectiveList { type Context = JsFormatContext; - fn format(node: &JsDirectiveList, formatter: &JsFormatter) -> FormatResult { - if !node.is_empty() { - let syntax_node = node.syntax(); - let next_sibling = syntax_node.next_sibling(); - // if next_sibling's first leading_trivia has more than one new_line, we should add an extra empty line at the end of - // JsDirectiveList, for example: - //```js - // "use strict"; <- first leading new_line - // <- second leading new_line - // function foo() { - - // } - //``` - // so we should keep an extra empty line after JsDirectiveList - let need_extra_empty_line = if let Some(next_sibling) = next_sibling { - get_lines_before(&next_sibling) > 1 - } else { - false - }; - formatted![ - formatter, - [ - formatter.format_list(node), - hard_line_break(), - if need_extra_empty_line { - empty_line() - } else { - empty_element() - } - ] - ] + fn fmt(node: &JsDirectiveList, f: &mut JsFormatter) -> FormatResult<()> { + if node.is_empty() { + return Ok(()); + } + + let syntax_node = node.syntax(); + let next_sibling = syntax_node.next_sibling(); + // if next_sibling's first leading_trivia has more than one new_line, we should add an extra empty line at the end of + // JsDirectiveList, for example: + //```js + // "use strict"; <- first leading new_line + // <- second leading new_line + // function foo() { + + // } + //``` + // so we should keep an extra empty line after JsDirectiveList + let need_extra_empty_line = if let Some(next_sibling) = next_sibling { + get_lines_before(&next_sibling) > 1 + } else { + false + }; + + let mut join = f.join_nodes_with_hardline(); + + for directive in node { + join.entry(directive.syntax(), &directive.format()); + } + + join.finish()?; + + if need_extra_empty_line { + write!(f, [empty_line()]) } else { - Ok(empty_element()) + write!(f, [hard_line_break()]) } } } diff --git a/crates/rome_js_formatter/src/js/lists/export_named_from_specifier_list.rs b/crates/rome_js_formatter/src/js/lists/export_named_from_specifier_list.rs index c2ea7c74600..04ec5536df4 100644 --- a/crates/rome_js_formatter/src/js/lists/export_named_from_specifier_list.rs +++ b/crates/rome_js_formatter/src/js/lists/export_named_from_specifier_list.rs @@ -5,13 +5,9 @@ use rome_js_syntax::JsExportNamedFromSpecifierList; impl FormatRule for FormatJsExportNamedFromSpecifierList { type Context = JsFormatContext; - fn format( - node: &JsExportNamedFromSpecifierList, - formatter: &JsFormatter, - ) -> FormatResult { - Ok(join_elements( - soft_line_break_or_space(), - formatter.format_separated(node, || token(","))?, - )) + fn fmt(node: &JsExportNamedFromSpecifierList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&soft_line_break_or_space()) + .entries(node.format_separated(token(","))) + .finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/export_named_specifier_list.rs b/crates/rome_js_formatter/src/js/lists/export_named_specifier_list.rs index 7cf8e136004..d7700cbf69a 100644 --- a/crates/rome_js_formatter/src/js/lists/export_named_specifier_list.rs +++ b/crates/rome_js_formatter/src/js/lists/export_named_specifier_list.rs @@ -5,13 +5,9 @@ use rome_js_syntax::JsExportNamedSpecifierList; impl FormatRule for FormatJsExportNamedSpecifierList { type Context = JsFormatContext; - fn format( - node: &JsExportNamedSpecifierList, - formatter: &JsFormatter, - ) -> FormatResult { - Ok(join_elements( - soft_line_break_or_space(), - formatter.format_separated(node, || token(","))?, - )) + fn fmt(node: &JsExportNamedSpecifierList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&soft_line_break_or_space()) + .entries(node.format_separated(token(","))) + .finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/import_assertion_entry_list.rs b/crates/rome_js_formatter/src/js/lists/import_assertion_entry_list.rs index c26f8211837..8c2a96d7711 100644 --- a/crates/rome_js_formatter/src/js/lists/import_assertion_entry_list.rs +++ b/crates/rome_js_formatter/src/js/lists/import_assertion_entry_list.rs @@ -5,13 +5,9 @@ use rome_js_syntax::JsImportAssertionEntryList; impl FormatRule for FormatJsImportAssertionEntryList { type Context = JsFormatContext; - fn format( - node: &JsImportAssertionEntryList, - formatter: &JsFormatter, - ) -> FormatResult { - Ok(join_elements( - soft_line_break_or_space(), - formatter.format_separated(node, || token(","))?, - )) + fn fmt(node: &JsImportAssertionEntryList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&soft_line_break_or_space()) + .entries(node.format_separated(token(","))) + .finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/method_modifier_list.rs b/crates/rome_js_formatter/src/js/lists/method_modifier_list.rs index e02edb5d5f2..04d10182098 100644 --- a/crates/rome_js_formatter/src/js/lists/method_modifier_list.rs +++ b/crates/rome_js_formatter/src/js/lists/method_modifier_list.rs @@ -6,10 +6,9 @@ use rome_js_syntax::JsMethodModifierList; impl FormatRule for FormatJsMethodModifierList { type Context = JsFormatContext; - fn format(node: &JsMethodModifierList, formatter: &JsFormatter) -> FormatResult { - Ok(join_elements( - space_token(), - formatter.format_all(sort_modifiers_by_precedence(node).into_iter().formatted())?, - )) + fn fmt(node: &JsMethodModifierList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&space_token()) + .entries(sort_modifiers_by_precedence(node).into_iter().formatted()) + .finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/module_item_list.rs b/crates/rome_js_formatter/src/js/lists/module_item_list.rs index ffc82a8f1fd..5ce2fb97aa9 100644 --- a/crates/rome_js_formatter/src/js/lists/module_item_list.rs +++ b/crates/rome_js_formatter/src/js/lists/module_item_list.rs @@ -5,7 +5,13 @@ use rome_js_syntax::JsModuleItemList; impl FormatRule for FormatJsModuleItemList { type Context = JsFormatContext; - fn format(node: &JsModuleItemList, formatter: &JsFormatter) -> FormatResult { - Ok(formatter.format_list(node)) + fn fmt(node: &JsModuleItemList, f: &mut JsFormatter) -> FormatResult<()> { + let mut join = f.join_nodes_with_hardline(); + + for module_item in node { + join.entry(module_item.syntax(), &format_or_verbatim(&module_item)); + } + + join.finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/named_import_specifier_list.rs b/crates/rome_js_formatter/src/js/lists/named_import_specifier_list.rs index 12ee5002aea..71562503e20 100644 --- a/crates/rome_js_formatter/src/js/lists/named_import_specifier_list.rs +++ b/crates/rome_js_formatter/src/js/lists/named_import_specifier_list.rs @@ -5,13 +5,9 @@ use rome_js_syntax::JsNamedImportSpecifierList; impl FormatRule for FormatJsNamedImportSpecifierList { type Context = JsFormatContext; - fn format( - node: &JsNamedImportSpecifierList, - formatter: &JsFormatter, - ) -> FormatResult { - Ok(join_elements( - soft_line_break_or_space(), - formatter.format_separated(node, || token(","))?, - )) + fn fmt(node: &JsNamedImportSpecifierList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&soft_line_break_or_space()) + .entries(node.format_separated(token(","))) + .finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/object_assignment_pattern_property_list.rs b/crates/rome_js_formatter/src/js/lists/object_assignment_pattern_property_list.rs index 4ec03d5493e..3e0767811bb 100644 --- a/crates/rome_js_formatter/src/js/lists/object_assignment_pattern_property_list.rs +++ b/crates/rome_js_formatter/src/js/lists/object_assignment_pattern_property_list.rs @@ -1,4 +1,3 @@ -use crate::formatter::{FormatSeparatedOptions, TrailingSeparator}; use crate::generated::FormatJsObjectAssignmentPatternPropertyList; use crate::prelude::*; use rome_js_syntax::{JsAnyObjectAssignmentPatternMember, JsObjectAssignmentPatternPropertyList}; @@ -8,10 +7,7 @@ impl FormatRule { type Context = JsFormatContext; - fn format( - node: &JsObjectAssignmentPatternPropertyList, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt(node: &JsObjectAssignmentPatternPropertyList, f: &mut JsFormatter) -> FormatResult<()> { // The trailing separator is disallowed after a rest element let has_trailing_rest = match node.into_iter().last() { Some(elem) => matches!( @@ -27,13 +23,10 @@ impl FormatRule TrailingSeparator::Allowed }; - Ok(join_elements( - soft_line_break_or_space(), - formatter.format_separated_with_options( - node, - || token(","), + f.join_with(&soft_line_break_or_space()) + .entries(node.format_separated(token(",")).with_options( FormatSeparatedOptions::default().with_trailing_separator(trailing_separator), - )?, - )) + )) + .finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/object_binding_pattern_property_list.rs b/crates/rome_js_formatter/src/js/lists/object_binding_pattern_property_list.rs index 682cf4a676f..5430bfe89d1 100644 --- a/crates/rome_js_formatter/src/js/lists/object_binding_pattern_property_list.rs +++ b/crates/rome_js_formatter/src/js/lists/object_binding_pattern_property_list.rs @@ -1,4 +1,3 @@ -use crate::formatter::{FormatSeparatedOptions, TrailingSeparator}; use crate::generated::FormatJsObjectBindingPatternPropertyList; use crate::prelude::*; use rome_js_syntax::{JsAnyObjectBindingPatternMember, JsObjectBindingPatternPropertyList}; @@ -6,10 +5,7 @@ use rome_js_syntax::{JsAnyObjectBindingPatternMember, JsObjectBindingPatternProp impl FormatRule for FormatJsObjectBindingPatternPropertyList { type Context = JsFormatContext; - fn format( - node: &JsObjectBindingPatternPropertyList, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt(node: &JsObjectBindingPatternPropertyList, f: &mut JsFormatter) -> FormatResult<()> { // The trailing separator is disallowed after a rest element let has_trailing_rest = match node.into_iter().last() { Some(elem) => matches!( @@ -25,13 +21,10 @@ impl FormatRule for FormatJsObjectBindingPat TrailingSeparator::Allowed }; - Ok(join_elements( - soft_line_break_or_space(), - formatter.format_separated_with_options( - node, - || token(","), + f.join_with(&soft_line_break_or_space()) + .entries(node.format_separated(token(",")).with_options( FormatSeparatedOptions::default().with_trailing_separator(trailing_separator), - )?, - )) + )) + .finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/object_member_list.rs b/crates/rome_js_formatter/src/js/lists/object_member_list.rs index 149b4c60400..974425bd71f 100644 --- a/crates/rome_js_formatter/src/js/lists/object_member_list.rs +++ b/crates/rome_js_formatter/src/js/lists/object_member_list.rs @@ -6,14 +6,13 @@ use rome_rowan::{AstNode, AstSeparatedList}; impl FormatRule for FormatJsObjectMemberList { type Context = JsFormatContext; - fn format(node: &JsObjectMemberList, formatter: &JsFormatter) -> FormatResult { - let members = formatter.format_separated(node, || token(","))?; + fn fmt(node: &JsObjectMemberList, f: &mut JsFormatter) -> FormatResult<()> { + let mut join = f.join_nodes_with_soft_line(); - Ok(join_elements_soft_line( - node.elements() - // This unwrap is guarded by the call to format_separated above - .map(|node| node.node().unwrap().syntax().clone()) - .zip(members), - )) + for (element, formatted) in node.elements().zip(node.format_separated(token(","))) { + join.entry(element.node()?.syntax(), &formatted); + } + + join.finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/parameter_list.rs b/crates/rome_js_formatter/src/js/lists/parameter_list.rs index 3b436a09b98..4c07e877273 100644 --- a/crates/rome_js_formatter/src/js/lists/parameter_list.rs +++ b/crates/rome_js_formatter/src/js/lists/parameter_list.rs @@ -1,4 +1,3 @@ -use crate::formatter::{FormatSeparatedOptions, TrailingSeparator}; use crate::generated::FormatJsParameterList; use crate::prelude::*; use rome_js_syntax::{JsAnyParameter, JsParameterList}; @@ -6,7 +5,7 @@ use rome_js_syntax::{JsAnyParameter, JsParameterList}; impl FormatRule for FormatJsParameterList { type Context = JsFormatContext; - fn format(node: &JsParameterList, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsParameterList, f: &mut JsFormatter) -> FormatResult<()> { // The trailing separator is disallowed if the last element in the list is a rest parameter let has_trailing_rest = match node.into_iter().last() { Some(elem) => matches!(elem?, JsAnyParameter::JsRestParameter(_)), @@ -19,13 +18,10 @@ impl FormatRule for FormatJsParameterList { TrailingSeparator::Allowed }; - Ok(join_elements( - soft_line_break_or_space(), - formatter.format_separated_with_options( - node, - || token(","), + f.join_with(&soft_line_break_or_space()) + .entries(node.format_separated(token(",")).with_options( FormatSeparatedOptions::default().with_trailing_separator(trailing_separator), - )?, - )) + )) + .finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/property_modifier_list.rs b/crates/rome_js_formatter/src/js/lists/property_modifier_list.rs index 736c0e14298..5e7f3762978 100644 --- a/crates/rome_js_formatter/src/js/lists/property_modifier_list.rs +++ b/crates/rome_js_formatter/src/js/lists/property_modifier_list.rs @@ -6,13 +6,9 @@ use rome_js_syntax::JsPropertyModifierList; impl FormatRule for FormatJsPropertyModifierList { type Context = JsFormatContext; - fn format( - node: &JsPropertyModifierList, - formatter: &JsFormatter, - ) -> FormatResult { - Ok(join_elements( - space_token(), - formatter.format_all(sort_modifiers_by_precedence(node).into_iter().formatted())?, - )) + fn fmt(node: &JsPropertyModifierList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&space_token()) + .entries(sort_modifiers_by_precedence(node).into_iter().formatted()) + .finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/statement_list.rs b/crates/rome_js_formatter/src/js/lists/statement_list.rs index 242e571c6b9..d03a1ad39ba 100644 --- a/crates/rome_js_formatter/src/js/lists/statement_list.rs +++ b/crates/rome_js_formatter/src/js/lists/statement_list.rs @@ -5,7 +5,13 @@ use rome_js_syntax::JsStatementList; impl FormatRule for FormatJsStatementList { type Context = JsFormatContext; - fn format(node: &JsStatementList, formatter: &JsFormatter) -> FormatResult { - Ok(formatter.format_list(node)) + fn fmt(node: &JsStatementList, f: &mut JsFormatter) -> FormatResult<()> { + let mut join = f.join_nodes_with_hardline(); + + for statement in node.iter() { + join.entry(statement.syntax(), &format_or_verbatim(&statement)); + } + + join.finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/switch_case_list.rs b/crates/rome_js_formatter/src/js/lists/switch_case_list.rs index 9c73b2838d7..d755d7038c8 100644 --- a/crates/rome_js_formatter/src/js/lists/switch_case_list.rs +++ b/crates/rome_js_formatter/src/js/lists/switch_case_list.rs @@ -5,7 +5,13 @@ use rome_js_syntax::JsSwitchCaseList; impl FormatRule for FormatJsSwitchCaseList { type Context = JsFormatContext; - fn format(node: &JsSwitchCaseList, formatter: &JsFormatter) -> FormatResult { - Ok(formatter.format_list(node)) + fn fmt(node: &JsSwitchCaseList, f: &mut JsFormatter) -> FormatResult<()> { + let mut join = f.join_nodes_with_hardline(); + + for case in node { + join.entry(case.syntax(), &format_or_verbatim(&case)); + } + + join.finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/template_element_list.rs b/crates/rome_js_formatter/src/js/lists/template_element_list.rs index 88037e0d0ee..707d544cf54 100644 --- a/crates/rome_js_formatter/src/js/lists/template_element_list.rs +++ b/crates/rome_js_formatter/src/js/lists/template_element_list.rs @@ -5,14 +5,13 @@ use rome_js_syntax::JsTemplateElementList; impl FormatRule for FormatJsTemplateElementList { type Context = JsFormatContext; - fn format( - node: &JsTemplateElementList, - formatter: &JsFormatter, - ) -> FormatResult { - Ok(concat_elements( - formatter - .format_all(node.iter().formatted())? - .map(group_elements), - )) + fn fmt(node: &JsTemplateElementList, f: &mut JsFormatter) -> FormatResult<()> { + let mut join = f.join(); + + for element in node { + join.entry(&element.format()); + } + + join.finish() } } diff --git a/crates/rome_js_formatter/src/js/lists/variable_declarator_list.rs b/crates/rome_js_formatter/src/js/lists/variable_declarator_list.rs index edd0efa44a7..091330524bf 100644 --- a/crates/rome_js_formatter/src/js/lists/variable_declarator_list.rs +++ b/crates/rome_js_formatter/src/js/lists/variable_declarator_list.rs @@ -1,4 +1,5 @@ use crate::prelude::*; +use rome_formatter::{format_args, write}; use crate::generated::FormatJsVariableDeclaratorList; use crate::AsFormat; @@ -8,54 +9,53 @@ use rome_rowan::AstSeparatedList; impl FormatRule for FormatJsVariableDeclaratorList { type Context = JsFormatContext; - fn format( - node: &JsVariableDeclaratorList, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt(node: &JsVariableDeclaratorList, f: &mut JsFormatter) -> FormatResult<()> { let last_index = node.len().saturating_sub(1); - let declarators = node - .elements() - .enumerate() - .map(|(index, element)| { - let node = formatted![formatter, [element.node()?.format()]]?; - let separator = match element.trailing_separator()? { + let mut declarators = node.elements().enumerate().map(|(index, element)| { + format_with(move |f| { + write!(f, [group_elements(&element.node().format())])?; + + match element.trailing_separator()? { None => { - if index == last_index { - empty_element() - } else { - token(",") + if index != last_index { + write!(f, [token(",")])?; } } Some(separator) => { - if index == last_index { - empty_element() - } else { - formatted![formatter, [separator.format()]]? + if index != last_index { + write!(f, [separator.format()])?; } } }; - Ok(format_elements![group_elements(node), separator]) + Ok(()) }) - .collect::>>()?; - - let mut items = declarators.into_iter(); - - let leading_element = items.next(); - let trailing_elements = join_elements(soft_line_break_or_space(), items); - - Ok(group_elements(concat_elements( - leading_element - .into_iter() - .chain(if !trailing_elements.is_empty() { - Some(indent(formatted![ - formatter, - [soft_line_break_or_space(), trailing_elements] - ]?)) - } else { - None - }), - ))) + }); + + let leading_element = declarators + .next() + .ok_or(FormatError::MissingRequiredChild)?; + + let other_declarators = format_once(|f| { + if node.len() == 1 { + // No more declarators, avoid single line break + return Ok(()); + } + + write!(f, [soft_line_break_or_space()])?; + + f.join_with(&soft_line_break_or_space()) + .entries(declarators) + .finish() + }); + + write!( + f, + [group_elements(&format_args!( + leading_element, + indent(&other_declarators) + ))] + ) } } diff --git a/crates/rome_js_formatter/src/js/module/default_import_specifier.rs b/crates/rome_js_formatter/src/js/module/default_import_specifier.rs index d9585a79031..13bb48372a1 100644 --- a/crates/rome_js_formatter/src/js/module/default_import_specifier.rs +++ b/crates/rome_js_formatter/src/js/module/default_import_specifier.rs @@ -1,22 +1,17 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsDefaultImportSpecifier; use rome_js_syntax::JsDefaultImportSpecifierFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsDefaultImportSpecifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsDefaultImportSpecifier, f: &mut JsFormatter) -> FormatResult<()> { let JsDefaultImportSpecifierFields { local_name, trailing_comma_token, } = node.as_fields(); - formatted![ - formatter, - [local_name.format(), trailing_comma_token.format()] - ] + write![f, [local_name.format(), trailing_comma_token.format()]] } } diff --git a/crates/rome_js_formatter/src/js/module/export.rs b/crates/rome_js_formatter/src/js/module/export.rs index dc6cce81747..54be3d0d925 100644 --- a/crates/rome_js_formatter/src/js/module/export.rs +++ b/crates/rome_js_formatter/src/js/module/export.rs @@ -1,18 +1,20 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsExport; use rome_js_syntax::JsExportFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsExport, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &JsExport, f: &mut JsFormatter) -> FormatResult<()> { let JsExportFields { export_token, export_clause, } = node.as_fields(); - let export_token = export_token.format(); - let export_clause = export_clause.format(); - formatted![formatter, [export_token, space_token(), export_clause]] + write![ + f, + [export_token.format(), space_token(), export_clause.format()] + ] } } diff --git a/crates/rome_js_formatter/src/js/module/export_as_clause.rs b/crates/rome_js_formatter/src/js/module/export_as_clause.rs index af4dbb9ab6f..8f2ca3e629c 100644 --- a/crates/rome_js_formatter/src/js/module/export_as_clause.rs +++ b/crates/rome_js_formatter/src/js/module/export_as_clause.rs @@ -1,22 +1,20 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsExportAsClause; use rome_js_syntax::JsExportAsClauseFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsExportAsClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsExportAsClause, f: &mut JsFormatter) -> FormatResult<()> { let JsExportAsClauseFields { as_token, exported_name, } = node.as_fields(); - let as_token = as_token.format(); - let exported_name = exported_name.format(); - - formatted![formatter, [as_token, space_token(), exported_name]] + write![ + f, + [as_token.format(), space_token(), exported_name.format()] + ] } } diff --git a/crates/rome_js_formatter/src/js/module/export_default_declaration_clause.rs b/crates/rome_js_formatter/src/js/module/export_default_declaration_clause.rs index 64fa2004b9e..9fb539aca1a 100644 --- a/crates/rome_js_formatter/src/js/module/export_default_declaration_clause.rs +++ b/crates/rome_js_formatter/src/js/module/export_default_declaration_clause.rs @@ -1,22 +1,23 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{JsExportDefaultDeclarationClause, JsExportDefaultDeclarationClauseFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( + fn fmt_fields( node: &JsExportDefaultDeclarationClause, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut JsFormatter, + ) -> FormatResult<()> { let JsExportDefaultDeclarationClauseFields { default_token, declaration, semicolon_token: _, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [default_token.format(), space_token(), declaration.format()] ] } diff --git a/crates/rome_js_formatter/src/js/module/export_default_expression_clause.rs b/crates/rome_js_formatter/src/js/module/export_default_expression_clause.rs index c8ce8f12965..389c157bafd 100644 --- a/crates/rome_js_formatter/src/js/module/export_default_expression_clause.rs +++ b/crates/rome_js_formatter/src/js/module/export_default_expression_clause.rs @@ -1,6 +1,7 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use rome_formatter::{format_args, write}; +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; use rome_js_syntax::JsExportDefaultExpressionClause; use rome_js_syntax::JsExportDefaultExpressionClauseFields; @@ -8,23 +9,19 @@ use rome_js_syntax::JsExportDefaultExpressionClauseFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsExportDefaultExpressionClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsExportDefaultExpressionClause, f: &mut JsFormatter) -> FormatResult<()> { let JsExportDefaultExpressionClauseFields { default_token, expression, semicolon_token, } = node.as_fields(); - let default_token = default_token.format(); - let class = expression.format(); - - format_with_semicolon( - formatter, - formatted![formatter, [default_token, space_token(), class]]?, - semicolon_token, + write!( + f, + [FormatWithSemicolon::new( + &format_args!(default_token.format(), space_token(), expression.format()), + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/js/module/export_from_clause.rs b/crates/rome_js_formatter/src/js/module/export_from_clause.rs index eb5f3dfba2e..ecfcd0b11f0 100644 --- a/crates/rome_js_formatter/src/js/module/export_from_clause.rs +++ b/crates/rome_js_formatter/src/js/module/export_from_clause.rs @@ -1,16 +1,13 @@ use crate::prelude::*; +use rome_formatter::{format_args, write}; -use crate::utils::format_with_semicolon; - +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; use rome_js_syntax::JsExportFromClause; use rome_js_syntax::JsExportFromClauseFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsExportFromClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsExportFromClause, f: &mut JsFormatter) -> FormatResult<()> { let JsExportFromClauseFields { star_token, export_as, @@ -20,26 +17,24 @@ impl FormatNodeFields for FormatNodeRule semicolon_token, } = node.as_fields(); - format_with_semicolon( - formatter, - formatted![ - formatter, - [ + write!( + f, + [FormatWithSemicolon::new( + &format_args!( star_token.format(), space_token(), export_as .format() - .with_or_empty(|as_token| formatted![formatter, [as_token, space_token()]]), + .with_or_empty(|as_token, f| write![f, [as_token, space_token()]]), from_token.format(), space_token(), source.format(), - assertion.format().with_or_empty(|assertion| formatted![ - formatter, - [space_token(), assertion] - ]), - ] - ]?, - semicolon_token, + assertion + .format() + .with_or_empty(|assertion, f| write![f, [space_token(), assertion]]), + ), + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/js/module/export_named_clause.rs b/crates/rome_js_formatter/src/js/module/export_named_clause.rs index b6e5cb4fcd9..4a0c8200955 100644 --- a/crates/rome_js_formatter/src/js/module/export_named_clause.rs +++ b/crates/rome_js_formatter/src/js/module/export_named_clause.rs @@ -1,16 +1,13 @@ use crate::prelude::*; +use rome_formatter::write; -use crate::utils::format_with_semicolon; - +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; use rome_js_syntax::JsExportNamedClause; use rome_js_syntax::JsExportNamedClauseFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsExportNamedClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsExportNamedClause, f: &mut JsFormatter) -> FormatResult<()> { let JsExportNamedClauseFields { type_token, l_curly_token, @@ -19,29 +16,25 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsExportNamedFromClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsExportNamedFromClause, f: &mut JsFormatter) -> FormatResult<()> { let JsExportNamedFromClauseFields { type_token, l_curly_token, @@ -23,46 +20,53 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsExportNamedFromSpecifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsExportNamedFromSpecifier, f: &mut JsFormatter) -> FormatResult<()> { let JsExportNamedFromSpecifierFields { type_token, source_name, export_as, } = node.as_fields(); - formatted![ - formatter, - [ - type_token - .format() - .with_or_empty(|type_token| formatted![formatter, [type_token, space_token()]]), - source_name.format(), - export_as - .format() - .with_or_empty(|export_as| formatted![formatter, [space_token(), export_as]]) - ] - ] + if let Some(type_token) = type_token { + write!(f, [type_token.format(), space_token()])?; + } + + write!(f, [source_name.format()])?; + + if let Some(export_as) = export_as { + write!(f, [space_token(), export_as.format()])?; + } + + Ok(()) } } diff --git a/crates/rome_js_formatter/src/js/module/export_named_shorthand_specifier.rs b/crates/rome_js_formatter/src/js/module/export_named_shorthand_specifier.rs index 6e8d6bcf7b6..03345144f70 100644 --- a/crates/rome_js_formatter/src/js/module/export_named_shorthand_specifier.rs +++ b/crates/rome_js_formatter/src/js/module/export_named_shorthand_specifier.rs @@ -1,4 +1,5 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsExportNamedShorthandSpecifier; @@ -7,20 +8,13 @@ use rome_js_syntax::JsExportNamedShorthandSpecifierFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsExportNamedShorthandSpecifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsExportNamedShorthandSpecifier, f: &mut JsFormatter) -> FormatResult<()> { let JsExportNamedShorthandSpecifierFields { type_token, name } = node.as_fields(); - formatted![ - formatter, - [ - type_token - .format() - .with_or_empty(|type_token| formatted![formatter, [type_token, space_token()]]), - name.format() - ] - ] + if let Some(type_token) = type_token { + write!(f, [type_token.format(), space_token()])?; + } + + write![f, [name.format()]] } } diff --git a/crates/rome_js_formatter/src/js/module/export_named_specifier.rs b/crates/rome_js_formatter/src/js/module/export_named_specifier.rs index e16589702c7..bec8a755043 100644 --- a/crates/rome_js_formatter/src/js/module/export_named_specifier.rs +++ b/crates/rome_js_formatter/src/js/module/export_named_specifier.rs @@ -1,14 +1,12 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsExportNamedSpecifier; use rome_js_syntax::JsExportNamedSpecifierFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsExportNamedSpecifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsExportNamedSpecifier, f: &mut JsFormatter) -> FormatResult<()> { let JsExportNamedSpecifierFields { type_token, local_name, @@ -16,12 +14,13 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields(node: &JsImport, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &JsImport, f: &mut JsFormatter) -> FormatResult<()> { let JsImportFields { import_token, import_clause, semicolon_token, } = node.as_fields(); - let import_token = import_token.format(); - let import_clause = import_clause.format(); - - format_with_semicolon( - formatter, - formatted![formatter, [import_token, space_token(), import_clause]]?, - semicolon_token, + write!( + f, + [FormatWithSemicolon::new( + &format_args!(import_token.format(), space_token(), import_clause.format()), + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/js/module/import_assertion.rs b/crates/rome_js_formatter/src/js/module/import_assertion.rs index 066a73e6c44..fef10d16da7 100644 --- a/crates/rome_js_formatter/src/js/module/import_assertion.rs +++ b/crates/rome_js_formatter/src/js/module/import_assertion.rs @@ -1,14 +1,11 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsImportAssertion; use rome_js_syntax::JsImportAssertionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsImportAssertion, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsImportAssertion, f: &mut JsFormatter) -> FormatResult<()> { let JsImportAssertionFields { assert_token, l_curly_token, @@ -16,15 +13,14 @@ impl FormatNodeFields for FormatNodeRule { r_curly_token, } = node.as_fields(); - let result = formatter - .delimited( - &l_curly_token?, - formatted![formatter, [assertions.format()]]?, - &r_curly_token?, - ) - .soft_block_spaces() - .finish()?; + write![f, [assert_token.format(), space_token()]]?; - formatted![formatter, [assert_token.format(), space_token(), result]] + write!( + f, + [ + format_delimited(&l_curly_token?, &assertions.format(), &r_curly_token?,) + .soft_block_spaces() + ] + ) } } diff --git a/crates/rome_js_formatter/src/js/module/import_assertion_entry.rs b/crates/rome_js_formatter/src/js/module/import_assertion_entry.rs index aeb06888105..ab1ac0019b7 100644 --- a/crates/rome_js_formatter/src/js/module/import_assertion_entry.rs +++ b/crates/rome_js_formatter/src/js/module/import_assertion_entry.rs @@ -1,14 +1,13 @@ use crate::prelude::*; +use rome_formatter::write; + use crate::utils::{FormatLiteralStringToken, StringLiteralParentKind}; use crate::FormatNodeFields; use rome_js_syntax::JsImportAssertionEntryFields; use rome_js_syntax::{JsImportAssertionEntry, JsSyntaxKind}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsImportAssertionEntry, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsImportAssertionEntry, f: &mut JsFormatter) -> FormatResult<()> { let JsImportAssertionEntryFields { key, colon_token, @@ -17,24 +16,27 @@ impl FormatNodeFields for FormatNodeRule formatted![ - formatter, - [FormatLiteralStringToken::new( - &key, - StringLiteralParentKind::Expression - )] - ]?, - _ => formatted![formatter, [key.format()]]?, + match key.kind() { + JsSyntaxKind::JS_STRING_LITERAL => { + write!( + f, + [FormatLiteralStringToken::new( + &key, + StringLiteralParentKind::Expression + )] + )?; + } + _ => { + write![f, [key.format()]]?; + } }; - formatted![ - formatter, + write![ + f, [ - formatted_key, colon_token.format(), space_token(), - FormatLiteralStringToken::new(&value_token?, StringLiteralParentKind::Expression) + FormatLiteralStringToken::new(&value_token?, StringLiteralParentKind::Expression), ] ] } diff --git a/crates/rome_js_formatter/src/js/module/import_bare_clause.rs b/crates/rome_js_formatter/src/js/module/import_bare_clause.rs index b01b4286bf0..6730d65b786 100644 --- a/crates/rome_js_formatter/src/js/module/import_bare_clause.rs +++ b/crates/rome_js_formatter/src/js/module/import_bare_clause.rs @@ -1,24 +1,19 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsImportBareClause; use rome_js_syntax::JsImportBareClauseFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsImportBareClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsImportBareClause, f: &mut JsFormatter) -> FormatResult<()> { let JsImportBareClauseFields { source, assertion } = node.as_fields(); - formatted![ - formatter, - [ - source.format(), - assertion - .format() - .with_or_empty(|assertion| formatted![formatter, [space_token(), assertion]]) - ] - ] + write!(f, [source.format()])?; + + if let Some(assertion) = assertion { + write!(f, [space_token(), assertion.format()])?; + } + + Ok(()) } } diff --git a/crates/rome_js_formatter/src/js/module/import_default_clause.rs b/crates/rome_js_formatter/src/js/module/import_default_clause.rs index d1076ac4ed1..10a11a953d0 100644 --- a/crates/rome_js_formatter/src/js/module/import_default_clause.rs +++ b/crates/rome_js_formatter/src/js/module/import_default_clause.rs @@ -1,14 +1,11 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsImportDefaultClause; use rome_js_syntax::JsImportDefaultClauseFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsImportDefaultClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsImportDefaultClause, f: &mut JsFormatter) -> FormatResult<()> { let JsImportDefaultClauseFields { type_token, local_name, @@ -17,21 +14,25 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields(node: &ImportMeta, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &ImportMeta, f: &mut JsFormatter) -> FormatResult<()> { let ImportMetaFields { import_token, dot_token, meta_token, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ import_token.format(), dot_token.format(), diff --git a/crates/rome_js_formatter/src/js/module/import_named_clause.rs b/crates/rome_js_formatter/src/js/module/import_named_clause.rs index ab09b33e11d..695658c1434 100644 --- a/crates/rome_js_formatter/src/js/module/import_named_clause.rs +++ b/crates/rome_js_formatter/src/js/module/import_named_clause.rs @@ -1,14 +1,11 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsImportNamedClause; use rome_js_syntax::JsImportNamedClauseFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsImportNamedClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsImportNamedClause, f: &mut JsFormatter) -> FormatResult<()> { let JsImportNamedClauseFields { type_token, default_specifier, @@ -18,24 +15,29 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsImportNamespaceClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsImportNamespaceClause, f: &mut JsFormatter) -> FormatResult<()> { let JsImportNamespaceClauseFields { type_token, star_token, @@ -19,12 +16,13 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsLiteralExportName, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsLiteralExportName, f: &mut JsFormatter) -> FormatResult<()> { let JsLiteralExportNameFields { value } = node.as_fields(); - formatted![ - formatter, - [FormatLiteralStringToken::new( - &value?, - StringLiteralParentKind::Expression - )] - ] + let value = value?; + + if value.kind() == JS_STRING_LITERAL { + FormatLiteralStringToken::new(&value, StringLiteralParentKind::Expression).fmt(f) + } else { + value.format().fmt(f) + } } } diff --git a/crates/rome_js_formatter/src/js/module/module_source.rs b/crates/rome_js_formatter/src/js/module/module_source.rs index d9be5634bbd..025670dc0b5 100644 --- a/crates/rome_js_formatter/src/js/module/module_source.rs +++ b/crates/rome_js_formatter/src/js/module/module_source.rs @@ -1,22 +1,20 @@ use crate::prelude::*; use crate::utils::{FormatLiteralStringToken, StringLiteralParentKind}; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsModuleSource; use rome_js_syntax::JsModuleSourceFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsModuleSource, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsModuleSource, f: &mut JsFormatter) -> FormatResult<()> { let JsModuleSourceFields { value_token } = node.as_fields(); - formatted![ - formatter, + write!( + f, [FormatLiteralStringToken::new( &value_token?, StringLiteralParentKind::Expression )] - ] + ) } } diff --git a/crates/rome_js_formatter/src/js/module/named_import_specifier.rs b/crates/rome_js_formatter/src/js/module/named_import_specifier.rs index fc2d06199c5..c4be16c2730 100644 --- a/crates/rome_js_formatter/src/js/module/named_import_specifier.rs +++ b/crates/rome_js_formatter/src/js/module/named_import_specifier.rs @@ -1,14 +1,11 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsNamedImportSpecifier; use rome_js_syntax::JsNamedImportSpecifierFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsNamedImportSpecifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsNamedImportSpecifier, f: &mut JsFormatter) -> FormatResult<()> { let JsNamedImportSpecifierFields { type_token, name, @@ -16,12 +13,13 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsNamedImportSpecifiers, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsNamedImportSpecifiers, f: &mut JsFormatter) -> FormatResult<()> { let JsNamedImportSpecifiersFields { l_curly_token, specifiers, r_curly_token, } = node.as_fields(); - formatter - .delimited( - &l_curly_token?, - formatted![formatter, [specifiers.format()]]?, - &r_curly_token?, - ) - .soft_block_spaces() - .finish() + write!( + f, + [ + format_delimited(&l_curly_token?, &specifiers.format(), &r_curly_token?,) + .soft_block_spaces() + ] + ) } } diff --git a/crates/rome_js_formatter/src/js/module/namespace_import_specifier.rs b/crates/rome_js_formatter/src/js/module/namespace_import_specifier.rs index 3d171e7135a..d14cb7f01bd 100644 --- a/crates/rome_js_formatter/src/js/module/namespace_import_specifier.rs +++ b/crates/rome_js_formatter/src/js/module/namespace_import_specifier.rs @@ -1,27 +1,26 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsNamespaceImportSpecifier; use rome_js_syntax::JsNamespaceImportSpecifierFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsNamespaceImportSpecifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsNamespaceImportSpecifier, f: &mut JsFormatter) -> FormatResult<()> { let JsNamespaceImportSpecifierFields { star_token, as_token, local_name, } = node.as_fields(); - let star = star_token.format(); - let as_token = as_token.format(); - let local_name = local_name.format(); - - formatted![ - formatter, - [star, space_token(), as_token, space_token(), local_name] + write![ + f, + [ + star_token.format(), + space_token(), + as_token.format(), + space_token(), + local_name.format() + ] ] } } diff --git a/crates/rome_js_formatter/src/js/module/shorthand_named_import_specifier.rs b/crates/rome_js_formatter/src/js/module/shorthand_named_import_specifier.rs index 271d5ff5c84..35e027a6396 100644 --- a/crates/rome_js_formatter/src/js/module/shorthand_named_import_specifier.rs +++ b/crates/rome_js_formatter/src/js/module/shorthand_named_import_specifier.rs @@ -1,29 +1,22 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsShorthandNamedImportSpecifier; use rome_js_syntax::JsShorthandNamedImportSpecifierFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsShorthandNamedImportSpecifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsShorthandNamedImportSpecifier, f: &mut JsFormatter) -> FormatResult<()> { let JsShorthandNamedImportSpecifierFields { type_token, local_name, } = node.as_fields(); - formatted![ - formatter, - [ - type_token - .format() - .with_or_empty(|token| formatted![formatter, [token, space_token()]]), - local_name.format() - ] - ] + if let Some(type_token) = type_token { + write!(f, [type_token.format(), space_token()])?; + } + + write![f, [local_name.format()]] } } diff --git a/crates/rome_js_formatter/src/js/objects/computed_member_name.rs b/crates/rome_js_formatter/src/js/objects/computed_member_name.rs index a94628da3f4..4d415936473 100644 --- a/crates/rome_js_formatter/src/js/objects/computed_member_name.rs +++ b/crates/rome_js_formatter/src/js/objects/computed_member_name.rs @@ -1,22 +1,19 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsComputedMemberName; use rome_js_syntax::JsComputedMemberNameFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsComputedMemberName, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsComputedMemberName, f: &mut JsFormatter) -> FormatResult<()> { let JsComputedMemberNameFields { l_brack_token, expression, r_brack_token, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ l_brack_token.format(), expression.format(), diff --git a/crates/rome_js_formatter/src/js/objects/getter_object_member.rs b/crates/rome_js_formatter/src/js/objects/getter_object_member.rs index 0693fb912cb..aecfc17e392 100644 --- a/crates/rome_js_formatter/src/js/objects/getter_object_member.rs +++ b/crates/rome_js_formatter/src/js/objects/getter_object_member.rs @@ -1,14 +1,11 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsGetterObjectMember; use rome_js_syntax::JsGetterObjectMemberFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsGetterObjectMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsGetterObjectMember, f: &mut JsFormatter) -> FormatResult<()> { let JsGetterObjectMemberFields { get_token, name, @@ -18,8 +15,8 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsLiteralMemberName, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsLiteralMemberName, f: &mut JsFormatter) -> FormatResult<()> { let JsLiteralMemberNameFields { value } = node.as_fields(); let value = value?; match value.kind() { JsSyntaxKind::JS_STRING_LITERAL => { - formatted![ - formatter, + write![ + f, [FormatLiteralStringToken::new( &value, StringLiteralParentKind::Expression )] ] } - _ => formatted![formatter, [value.format()]], + _ => write![f, [value.format()]], } } } diff --git a/crates/rome_js_formatter/src/js/objects/method_object_member.rs b/crates/rome_js_formatter/src/js/objects/method_object_member.rs index efa52bd869f..8c2b08b8a8e 100644 --- a/crates/rome_js_formatter/src/js/objects/method_object_member.rs +++ b/crates/rome_js_formatter/src/js/objects/method_object_member.rs @@ -1,14 +1,12 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsMethodObjectMember; use rome_js_syntax::JsMethodObjectMemberFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsMethodObjectMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsMethodObjectMember, f: &mut JsFormatter) -> FormatResult<()> { let JsMethodObjectMemberFields { async_token, star_token, @@ -19,13 +17,13 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsPrivateClassMemberName, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsPrivateClassMemberName, f: &mut JsFormatter) -> FormatResult<()> { let JsPrivateClassMemberNameFields { hash_token, id_token, } = node.as_fields(); - formatted![formatter, [hash_token.format(), id_token.format(),]] + write![f, [hash_token.format(), id_token.format()]] } } diff --git a/crates/rome_js_formatter/src/js/objects/property_object_member.rs b/crates/rome_js_formatter/src/js/objects/property_object_member.rs index 4fdb95aa084..2537c304ccf 100644 --- a/crates/rome_js_formatter/src/js/objects/property_object_member.rs +++ b/crates/rome_js_formatter/src/js/objects/property_object_member.rs @@ -1,20 +1,19 @@ use crate::prelude::*; -use crate::utils::FormatMemberName; -use crate::utils::JsAnyBinaryLikeExpression; +use crate::utils::StringLiteralParentKind; +use crate::utils::{FormatLiteralStringToken, JsAnyBinaryLikeExpression}; use crate::FormatNodeFields; -use rome_js_syntax::JsAnyExpression; +use rome_formatter::{format_args, write}; use rome_js_syntax::JsAnyLiteralExpression; use rome_js_syntax::JsPropertyObjectMember; use rome_js_syntax::JsPropertyObjectMemberFields; +use rome_js_syntax::JsSyntaxKind::JS_STRING_LITERAL; +use rome_js_syntax::{JsAnyExpression, JsAnyObjectMemberName}; use rome_rowan::{AstNode, SyntaxResult}; use unicode_width::UnicodeWidthStr; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsPropertyObjectMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsPropertyObjectMember, f: &mut JsFormatter) -> FormatResult<()> { let JsPropertyObjectMemberFields { name, colon_token, @@ -22,64 +21,73 @@ impl FormatNodeFields for FormatNodeRule { - let group_id = formatter.group_id("property_object_member"); - - let value = formatted![formatter, [value.format()]]?; - formatted![ - formatter, - [ - group_elements(format_name), - colon_token.format(), - group_elements_with_options( - indent(soft_line_break_or_space()), - GroupElementsOptions { - group_id: Some(group_id), - } - ), - line_suffix_boundary(), - if_group_with_id_breaks(indent(value.clone()), group_id), - if_group_with_id_fits_on_line(value, group_id), + let value = value?; + let format_content = format_with(|f| { + let name_width = write_member_name(&name, f)?; + colon_token.format().fmt(f)?; + + let layout = property_object_member_layout(f, name_width, &value)?; + match layout { + PropertyObjectMemberLayout::Fluid => { + let group_id = f.group_id("property_object_member"); + + let value = value.format().memoized(); + + write![ + f, + [ + group_elements(&indent(&soft_line_break_or_space()),) + .with_group_id(Some(group_id)), + line_suffix_boundary(), + if_group_breaks(&indent(&value)).with_group_id(Some(group_id)), + if_group_fits_on_line(&value).with_group_id(Some(group_id)), + ] ] - ] - } - PropertyObjectMemberLayout::BreakAfterColon => { - formatted![ - formatter, - [ - group_elements(format_name), - colon_token.format(), - space_token(), - group_elements(formatted![ - formatter, - [indent(formatted![ - formatter, - [soft_line_break_or_space(), value.format()] - ]?)] - ]?), + } + PropertyObjectMemberLayout::BreakAfterColon => { + write![ + f, + [ + space_token(), + group_elements(&indent(&format_args![ + soft_line_break_or_space(), + value.format() + ])), + ] ] - ] + } + PropertyObjectMemberLayout::NeverBreakAfterColon => { + write![f, [space_token(), value.format(),]] + } + } + }); + + write!(f, [group_elements(&format_content)]) + } +} + +fn write_member_name(name: &JsAnyObjectMemberName, f: &mut JsFormatter) -> FormatResult { + match name { + name @ JsAnyObjectMemberName::JsLiteralMemberName(literal) => { + let value = literal.value()?; + + if value.kind() == JS_STRING_LITERAL { + let format = FormatLiteralStringToken::new(&value, StringLiteralParentKind::Member); + let cleaned = format.clean_text(f.context()); + + cleaned.fmt(f)?; + + Ok(cleaned.width()) + } else { + name.format().fmt(f)?; + + Ok(value.text_trimmed().width()) } - PropertyObjectMemberLayout::NeverBreakAfterColon => formatted![ - formatter, - [ - group_elements(format_name), - colon_token.format(), - space_token(), - value.format(), - ] - ], - }; - - Ok(group_elements(formatted?)) + } + name => { + write!(f, [group_elements(&name.format())])?; + Ok(name.text().width()) + } } } @@ -135,25 +143,21 @@ fn property_object_member_layout( let is_name_short = name_width < text_width_for_break; if is_break_after_colon(value)? { - return Ok(PropertyObjectMemberLayout::BreakAfterColon); - } - - if is_name_short { - return Ok(PropertyObjectMemberLayout::NeverBreakAfterColon); + Ok(PropertyObjectMemberLayout::BreakAfterColon) + } else if is_name_short { + Ok(PropertyObjectMemberLayout::NeverBreakAfterColon) } else if matches!( value, JsAnyExpression::JsAnyLiteralExpression(JsAnyLiteralExpression::JsStringLiteralExpression( _ )) ) { - return Ok(PropertyObjectMemberLayout::BreakAfterColon); - } - - if is_never_break_after_colon(value)? { - return Ok(PropertyObjectMemberLayout::NeverBreakAfterColon); + Ok(PropertyObjectMemberLayout::BreakAfterColon) + } else if is_never_break_after_colon(value)? { + Ok(PropertyObjectMemberLayout::NeverBreakAfterColon) + } else { + Ok(PropertyObjectMemberLayout::Fluid) } - - Ok(PropertyObjectMemberLayout::Fluid) } fn is_break_after_colon(value: &JsAnyExpression) -> SyntaxResult { diff --git a/crates/rome_js_formatter/src/js/objects/setter_object_member.rs b/crates/rome_js_formatter/src/js/objects/setter_object_member.rs index 391964c773b..c7f45d24d88 100644 --- a/crates/rome_js_formatter/src/js/objects/setter_object_member.rs +++ b/crates/rome_js_formatter/src/js/objects/setter_object_member.rs @@ -1,14 +1,11 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsSetterObjectMember; use rome_js_syntax::JsSetterObjectMemberFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsSetterObjectMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsSetterObjectMember, f: &mut JsFormatter) -> FormatResult<()> { let JsSetterObjectMemberFields { set_token, name, @@ -18,8 +15,8 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsShorthandPropertyObjectMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsShorthandPropertyObjectMember, f: &mut JsFormatter) -> FormatResult<()> { let JsShorthandPropertyObjectMemberFields { name } = node.as_fields(); - formatted![formatter, [name.format()]] + write![f, [name.format()]] } } diff --git a/crates/rome_js_formatter/src/js/statements/block_statement.rs b/crates/rome_js_formatter/src/js/statements/block_statement.rs index aa33df71e78..c161658e1a5 100644 --- a/crates/rome_js_formatter/src/js/statements/block_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/block_statement.rs @@ -1,7 +1,7 @@ use crate::prelude::*; - -use rome_js_syntax::JsAnyStatement; +use rome_formatter::{write, Buffer}; use rome_js_syntax::JsBlockStatement; +use rome_js_syntax::{JsAnyStatement, JsEmptyStatement}; use crate::FormatNodeFields; use rome_js_syntax::JsBlockStatementFields; @@ -9,32 +9,37 @@ use rome_js_syntax::JsSyntaxKind; use rome_rowan::{AstNode, AstNodeList}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsBlockStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsBlockStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsBlockStatementFields { l_curly_token, statements, r_curly_token, } = node.as_fields(); - let stmts = formatter.format_list(&statements); - if is_non_collapsable_empty_block(node) { - formatted![ - formatter, + for stmt in statements + .iter() + .filter_map(|stmt| JsEmptyStatement::cast(stmt.into_syntax())) + { + f.state_mut().track_token(&stmt.semicolon_token()?) + } + + write!( + f, [ l_curly_token.format(), hard_line_break(), r_curly_token.format() ] - ] + ) } else { - formatter - .delimited(&l_curly_token?, stmts, &r_curly_token?) - .block_indent() - .finish() + write!( + f, + [ + format_delimited(&l_curly_token?, &statements.format(), &r_curly_token?) + .block_indent() + ] + ) } } } @@ -80,10 +85,9 @@ fn is_non_collapsable_empty_block(block: &JsBlockStatement) -> bool { // } // ``` if !block.statements().is_empty() - && block - .statements() - .iter() - .any(|s| !matches!(s, JsAnyStatement::JsEmptyStatement(_))) + && block.statements().iter().any(|s| { + !matches!(s, JsAnyStatement::JsEmptyStatement(_)) || s.syntax().has_comments_direct() + }) { return false; } diff --git a/crates/rome_js_formatter/src/js/statements/break_statement.rs b/crates/rome_js_formatter/src/js/statements/break_statement.rs index 2ffd2050083..b4725043603 100644 --- a/crates/rome_js_formatter/src/js/statements/break_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/break_statement.rs @@ -1,33 +1,33 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use rome_formatter::write; +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; use rome_js_syntax::JsBreakStatement; use rome_js_syntax::JsBreakStatementFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsBreakStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsBreakStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsBreakStatementFields { break_token, label_token, semicolon_token, } = node.as_fields(); - format_with_semicolon( - formatter, - formatted![ - formatter, - [ - break_token.format(), - label_token - .format() - .with_or_empty(|label| formatted![formatter, [space_token(), label]]) - ] - ]?, - semicolon_token, + write!( + f, + [FormatWithSemicolon::new( + &format_with(|f| { + write!(f, [break_token.format()])?; + + if let Some(label_token) = &label_token { + write!(f, [space_token(), label_token.format()])?; + } + + Ok(()) + }), + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/js/statements/continue_statement.rs b/crates/rome_js_formatter/src/js/statements/continue_statement.rs index 7c6098cf2f5..edbfa0d1347 100644 --- a/crates/rome_js_formatter/src/js/statements/continue_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/continue_statement.rs @@ -1,33 +1,33 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use rome_formatter::write; +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; use rome_js_syntax::JsContinueStatement; use rome_js_syntax::JsContinueStatementFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsContinueStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsContinueStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsContinueStatementFields { continue_token, label_token, semicolon_token, } = node.as_fields(); - format_with_semicolon( - formatter, - formatted![ - formatter, - [ - continue_token.format(), - label_token - .format() - .with_or_empty(|token| formatted![formatter, [space_token(), token]]) - ] - ]?, - semicolon_token, + write!( + f, + [FormatWithSemicolon::new( + &format_with(|f| { + write!(f, [continue_token.format()])?; + + if let Some(label_token) = &label_token { + write!(f, [space_token(), label_token.format()])?; + } + + Ok(()) + }), + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/js/statements/debugger_statement.rs b/crates/rome_js_formatter/src/js/statements/debugger_statement.rs index 2312632aeed..366a3e38321 100644 --- a/crates/rome_js_formatter/src/js/statements/debugger_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/debugger_statement.rs @@ -1,24 +1,24 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use rome_formatter::{format_args, write}; +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; use rome_js_syntax::JsDebuggerStatement; use rome_js_syntax::JsDebuggerStatementFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsDebuggerStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsDebuggerStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsDebuggerStatementFields { debugger_token, semicolon_token, } = node.as_fields(); - format_with_semicolon( - formatter, - formatted![formatter, [debugger_token.format()]]?, - semicolon_token, + write!( + f, + [FormatWithSemicolon::new( + &format_args!(debugger_token.format()), + semicolon_token.as_ref() + ),] ) } } diff --git a/crates/rome_js_formatter/src/js/statements/do_while_statement.rs b/crates/rome_js_formatter/src/js/statements/do_while_statement.rs index dc809b76a9a..f0467e040d9 100644 --- a/crates/rome_js_formatter/src/js/statements/do_while_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/do_while_statement.rs @@ -1,14 +1,11 @@ use crate::prelude::*; - use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsDoWhileStatementFields; use rome_js_syntax::{JsAnyStatement, JsDoWhileStatement}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsDoWhileStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsDoWhileStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsDoWhileStatementFields { do_token, body, @@ -19,31 +16,31 @@ impl FormatNodeFields for FormatNodeRule semicolon_token, } = node.as_fields(); - let head = formatted![formatter, [do_token.format()]]?; + write!(f, [do_token.format()])?; + + match body? { + JsAnyStatement::JsEmptyStatement(body) => { + write!(f, [body.format(), hard_line_break()])?; + } + body => { + write!(f, [space_token(), body.format()])?; + } + }; - let tail = formatted![ - formatter, + write![ + f, [ space_token(), while_token.format(), space_token(), - formatter - .delimited( - &l_paren_token?, - formatted![formatter, [test.format()]]?, - &r_paren_token?, - ) - .soft_block_indent() - .finish()?, - semicolon_token.format().or_format(|| token(";")) + format_delimited(&l_paren_token?, &test.format(), &r_paren_token?,) + .soft_block_indent(), ] ]?; - let body = body?; - if matches!(body, JsAnyStatement::JsEmptyStatement(_)) { - formatted![formatter, [head, body.format(), hard_line_break(), tail,]] - } else { - formatted![formatter, [head, space_token(), body.format(), tail,]] + match semicolon_token { + Some(semicolon_token) => write!(f, [semicolon_token.format()]), + None => write!(f, [token(";")]), } } } diff --git a/crates/rome_js_formatter/src/js/statements/empty_statement.rs b/crates/rome_js_formatter/src/js/statements/empty_statement.rs index 1070796e995..406da324acc 100644 --- a/crates/rome_js_formatter/src/js/statements/empty_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/empty_statement.rs @@ -1,25 +1,24 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::{JsEmptyStatement, JsEmptyStatementFields, JsSyntaxKind}; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsEmptyStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsEmptyStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsEmptyStatementFields { semicolon_token } = node.as_fields(); let parent_kind = node.syntax().parent().map(|p| p.kind()); + if matches!( parent_kind, Some(JsSyntaxKind::JS_DO_WHILE_STATEMENT) | Some(JsSyntaxKind::JS_IF_STATEMENT) | Some(JsSyntaxKind::JS_ELSE_CLAUSE) ) { - formatted![formatter, [semicolon_token.format()]] + write!(f, [semicolon_token.format()]) } else { - Ok(formatter.format_replaced(&semicolon_token?, empty_element())) + write!(f, [format_replaced(&semicolon_token?, &empty_element())]) } } } diff --git a/crates/rome_js_formatter/src/js/statements/expression_statement.rs b/crates/rome_js_formatter/src/js/statements/expression_statement.rs index f61a91861fa..1de248cd68a 100644 --- a/crates/rome_js_formatter/src/js/statements/expression_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/expression_statement.rs @@ -1,24 +1,24 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use rome_formatter::{format_args, write}; +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; use rome_js_syntax::JsExpressionStatement; use rome_js_syntax::JsExpressionStatementFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsExpressionStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsExpressionStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsExpressionStatementFields { expression, semicolon_token, } = node.as_fields(); - format_with_semicolon( - formatter, - formatted![formatter, [expression.format()]]?, - semicolon_token, + write!( + f, + [FormatWithSemicolon::new( + &format_args!(expression.format()), + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/js/statements/for_in_statement.rs b/crates/rome_js_formatter/src/js/statements/for_in_statement.rs index 22c5c0ffcba..9cdc777f669 100644 --- a/crates/rome_js_formatter/src/js/statements/for_in_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/for_in_statement.rs @@ -1,15 +1,12 @@ -use rome_js_syntax::JsForInStatement; - use crate::prelude::*; -use crate::utils::format_head_body_statement; +use crate::utils::FormatBodyStatement; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; +use rome_js_syntax::JsForInStatement; use rome_js_syntax::JsForInStatementFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsForInStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsForInStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsForInStatementFields { for_token, l_paren_token, @@ -25,23 +22,20 @@ impl FormatNodeFields for FormatNodeRule { let in_token = in_token.format(); let expression = expression.format(); - Ok(group_elements(format_head_body_statement( - formatter, - formatted![ - formatter, - [ - for_token, - space_token(), - l_paren_token.format(), - group_elements(formatted![formatter, [initializer]]?), - space_token(), - in_token, - space_token(), - expression, - r_paren_token.format(), - ] - ]?, - body?, - )?)) + write!( + f, + [group_elements(&format_args!( + for_token, + space_token(), + l_paren_token.format(), + group_elements(&initializer), + space_token(), + in_token, + space_token(), + expression, + r_paren_token.format(), + FormatBodyStatement::new(&body?) + ))] + ) } } diff --git a/crates/rome_js_formatter/src/js/statements/for_of_statement.rs b/crates/rome_js_formatter/src/js/statements/for_of_statement.rs index 3368d1db124..f91811d6bc5 100644 --- a/crates/rome_js_formatter/src/js/statements/for_of_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/for_of_statement.rs @@ -1,16 +1,13 @@ -use rome_js_syntax::JsForOfStatement; - use crate::prelude::*; -use crate::utils::format_head_body_statement; +use crate::utils::FormatBodyStatement; +use rome_formatter::{format_args, write}; +use rome_js_syntax::JsForOfStatement; use crate::FormatNodeFields; use rome_js_syntax::JsForOfStatementFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsForOfStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsForOfStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsForOfStatementFields { for_token, await_token, @@ -22,26 +19,23 @@ impl FormatNodeFields for FormatNodeRule { body, } = node.as_fields(); - Ok(group_elements(format_head_body_statement( - formatter, - formatted![ - formatter, - [ - for_token.format(), - space_token(), - await_token - .format() - .with_or_empty(|token| formatted![formatter, [token, space_token()]]), - l_paren_token.format(), - group_elements(formatted![formatter, [initializer.format()]]?), - space_token(), - of_token.format(), - space_token(), - expression.format(), - r_paren_token.format() - ] - ]?, - body?, - )?)) + write!( + f, + [group_elements(&format_args![ + for_token.format(), + space_token(), + await_token + .format() + .with_or_empty(|token, f| write![f, [token, space_token()]]), + l_paren_token.format(), + group_elements(&initializer.format()), + space_token(), + of_token.format(), + space_token(), + expression.format(), + r_paren_token.format(), + FormatBodyStatement::new(&body?) + ])] + ) } } diff --git a/crates/rome_js_formatter/src/js/statements/for_statement.rs b/crates/rome_js_formatter/src/js/statements/for_statement.rs index b7220781af7..979dbc26498 100644 --- a/crates/rome_js_formatter/src/js/statements/for_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/for_statement.rs @@ -1,4 +1,5 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsAnyStatement; @@ -6,10 +7,7 @@ use rome_js_syntax::JsForStatement; use rome_js_syntax::JsForStatementFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsForStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsForStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsForStatementFields { for_token, l_paren_token, @@ -22,45 +20,47 @@ impl FormatNodeFields for FormatNodeRule { body, } = node.as_fields(); - let inner = if initializer.is_some() || test.is_some() || update.is_some() { - formatted![ - formatter, + let condition = format_with(|f| { + if initializer.is_some() || test.is_some() || update.is_some() { + write![ + f, + [ + initializer.format(), + first_semi_token.format(), + soft_line_break_or_space(), + test.format(), + second_semi_token.format(), + soft_line_break_or_space(), + update.format(), + ] + ] + } else { + write![f, [first_semi_token.format(), second_semi_token.format()]] + } + }); + + let content = format_with(|f| { + write!( + f, [ - initializer.format(), - first_semi_token.format(), - soft_line_break_or_space(), - test.format(), - second_semi_token.format(), - soft_line_break_or_space(), - update.format(), + for_token.format(), + space_token(), + format_delimited(l_paren_token.as_ref()?, &condition, r_paren_token.as_ref()?,) + .soft_block_indent(), ] - ]? - } else { - formatted![ - formatter, - [first_semi_token.format(), second_semi_token.format(),] - ]? - }; + )?; - // Force semicolon insertion for empty bodies - let body = body?; - let body = if matches!(body, JsAnyStatement::JsEmptyStatement(_)) { - formatted![formatter, [body.format(), token(";")]]? - } else { - formatted![formatter, [space_token(), body.format()]]? - }; + // Force semicolon insertion for empty bodies + match body.as_ref()? { + JsAnyStatement::JsEmptyStatement(body) => { + write![f, [body.format(), token(";")]] + } + body => { + write!(f, [space_token(), body.format()]) + } + } + }); - Ok(group_elements(formatted![ - formatter, - [ - for_token.format(), - space_token(), - formatter - .delimited(&l_paren_token?, inner, &r_paren_token?,) - .soft_block_indent() - .finish()?, - body - ] - ]?)) + write!(f, [group_elements(&content)]) } } diff --git a/crates/rome_js_formatter/src/js/statements/if_statement.rs b/crates/rome_js_formatter/src/js/statements/if_statement.rs index 0048a8f8d27..b9aa9f6c44c 100644 --- a/crates/rome_js_formatter/src/js/statements/if_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/if_statement.rs @@ -1,4 +1,5 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsSyntaxToken; @@ -6,10 +7,9 @@ use rome_js_syntax::{JsAnyStatement, JsElseClauseFields, JsIfStatement}; use rome_js_syntax::{JsElseClause, JsIfStatementFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsIfStatement, formatter: &JsFormatter) -> FormatResult { - let (head, mut else_clause) = format_if_element(formatter, None, node)?; + fn fmt_fields(node: &JsIfStatement, f: &mut JsFormatter) -> FormatResult<()> { + let mut else_clause = write_if_element(f, None, node)?; - let mut if_chain = vec![head]; while let Some(clause) = else_clause.take() { let JsElseClauseFields { else_token, @@ -18,34 +18,27 @@ impl FormatNodeFields for FormatNodeRule { match alternate? { JsAnyStatement::JsIfStatement(stmt) => { - let (head, alternate) = format_if_element(formatter, Some(else_token?), &stmt)?; + let alternate = write_if_element(f, Some(else_token?), &stmt)?; - if_chain.push(head); else_clause = alternate; } alternate => { - if_chain.push(formatted![ - formatter, - [ - space_token(), - else_token.format(), - into_block(formatter, alternate)?, - ] - ]?); + write![f, [space_token(), else_token.format()]]?; + write_consequent_block(f, alternate)?; } } } - Ok(concat_elements(if_chain)) + Ok(()) } } /// Format a single `else? if(test) consequent` element, returning the next else clause -fn format_if_element( - formatter: &JsFormatter, +fn write_if_element( + f: &mut JsFormatter, else_token: Option, stmt: &JsIfStatement, -) -> FormatResult<(FormatElement, Option)> { +) -> FormatResult> { let JsIfStatementFields { if_token, l_paren_token, @@ -55,48 +48,42 @@ fn format_if_element( else_clause, } = stmt.as_fields(); - let head = formatted![ - formatter, + if let Some(else_token) = else_token { + write!(f, [space_token(), else_token.format(), space_token()])?; + } + + write![ + f, [ - else_token.format().with_or_empty(|token| formatted![ - formatter, - [space_token(), token, space_token(),] - ]), if_token.format(), space_token(), - formatter - .delimited( - &l_paren_token?, - formatted![formatter, [test.format()]]?, - &r_paren_token?, - ) - .soft_block_indent() - .finish()?, - into_block(formatter, consequent?)?, + format_delimited(&l_paren_token?, &test.format(), &r_paren_token?).soft_block_indent(), ] ]?; - Ok((head, else_clause)) + write_consequent_block(f, consequent?)?; + + Ok(else_clause) } /// Wraps the statement into a block if its not already a JsBlockStatement -fn into_block(formatter: &JsFormatter, stmt: JsAnyStatement) -> FormatResult { +fn write_consequent_block(f: &mut JsFormatter, stmt: JsAnyStatement) -> FormatResult<()> { if matches!(stmt, JsAnyStatement::JsBlockStatement(_)) { - return formatted![formatter, [space_token(), stmt.format()]]; + return write![f, [space_token(), stmt.format()]]; } // If the body is an empty statement, force a line break to ensure behavior // is coherent with `is_non_collapsable_empty_block` if matches!(stmt, JsAnyStatement::JsEmptyStatement(_)) { - return formatted![formatter, [stmt.format(), hard_line_break()]]; + return write![f, [stmt.format(), hard_line_break()]]; } - formatted![ - formatter, + write![ + f, [ space_token(), token("{"), - block_indent(formatted![formatter, [stmt.format()]]?), + block_indent(&stmt.format()), token("}"), ] ] diff --git a/crates/rome_js_formatter/src/js/statements/labeled_statement.rs b/crates/rome_js_formatter/src/js/statements/labeled_statement.rs index 495b3ad9c13..4c830deb3ce 100644 --- a/crates/rome_js_formatter/src/js/statements/labeled_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/labeled_statement.rs @@ -1,31 +1,28 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsLabeledStatementFields; use rome_js_syntax::{JsAnyStatement, JsLabeledStatement}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsLabeledStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsLabeledStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsLabeledStatementFields { label_token, colon_token, body, } = node.as_fields(); - let label = label_token.format(); - let colon = colon_token.format(); + write!(f, [label_token.format(), colon_token.format()])?; - let body = body?; - if matches!(body, JsAnyStatement::JsEmptyStatement(_)) { - // If the body is an empty statement, force semicolon insertion - let statement = body.format(); - formatted![formatter, [label, colon, statement, token(";")]] - } else { - let statement = body.format(); - formatted![formatter, [label, colon, space_token(), statement]] + match body? { + JsAnyStatement::JsEmptyStatement(empty) => { + // If the body is an empty statement, force semicolon insertion + write!(f, [empty.format(), token(";")]) + } + body => { + write!(f, [space_token(), body.format()]) + } } } } diff --git a/crates/rome_js_formatter/src/js/statements/return_statement.rs b/crates/rome_js_formatter/src/js/statements/return_statement.rs index b3611203a6f..8cb88e17fbe 100644 --- a/crates/rome_js_formatter/src/js/statements/return_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/return_statement.rs @@ -1,52 +1,44 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; -use rome_js_syntax::{JsReturnStatement, JsReturnStatementFields, JsSyntaxKind}; -use rome_rowan::AstNode; +use rome_formatter::{format_args, write}; +use rome_js_syntax::{JsAnyExpression, JsReturnStatement, JsReturnStatementFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsReturnStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsReturnStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsReturnStatementFields { return_token, argument, semicolon_token, } = node.as_fields(); - let return_token = return_token.format(); + write!( + f, + [FormatWithSemicolon::new( + &format_with(|f| { + write!(f, [return_token.format()])?; - let argument = if let Some(argument) = argument { - if matches!( - argument.syntax().kind(), - JsSyntaxKind::JS_SEQUENCE_EXPRESSION - ) { - formatted![ - formatter, - [ - space_token(), - group_elements(formatted![ - formatter, - [ - token("("), - soft_block_indent(formatted![formatter, [argument.format()]]?), - token(")") - ] - ]?), - ] - ]? - } else { - formatted![formatter, [space_token(), argument.format()]]? - } - } else { - empty_element() - }; + if let Some(argument) = &argument { + write!(f, [space_token()])?; - format_with_semicolon( - formatter, - formatted![formatter, [return_token, argument]]?, - semicolon_token, + if let JsAnyExpression::JsSequenceExpression(_expression) = argument { + write![ + f, + [group_elements(&format_args![ + token("("), + soft_block_indent(&argument.format()), + token(")") + ])] + ]?; + } else { + write![f, [argument.format()]]?; + } + } + + Ok(()) + }), + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/js/statements/switch_statement.rs b/crates/rome_js_formatter/src/js/statements/switch_statement.rs index dae9617ad3a..c61ff1cbeab 100644 --- a/crates/rome_js_formatter/src/js/statements/switch_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/switch_statement.rs @@ -1,13 +1,11 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{JsSwitchStatement, JsSwitchStatementFields}; -use rome_rowan::{AstNode, AstNodeList}; +use rome_rowan::AstNodeList; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsSwitchStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsSwitchStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsSwitchStatementFields { switch_token, l_paren_token, @@ -18,37 +16,25 @@ impl FormatNodeFields for FormatNodeRule { r_curly_token, } = node.as_fields(); - formatted![ - formatter, + let format_cases = format_with(|f| { + if cases.is_empty() { + hard_line_break().fmt(f)?; + } else { + cases.format().fmt(f)?; + } + + Ok(()) + }); + + write![ + f, [ switch_token.format(), space_token(), - formatter - .delimited( - &l_paren_token?, - formatted![formatter, [discriminant.format()]]?, - &r_paren_token?, - ) - .soft_block_indent() - .finish()?, + format_delimited(&l_paren_token?, &discriminant.format(), &r_paren_token?,) + .soft_block_indent(), space_token(), - formatter - .delimited( - &l_curly_token?, - if cases.is_empty() { - hard_line_break() - } else { - join_elements_hard_line( - cases - .iter() - .map(|node| node.syntax().clone()) - .zip(formatter.format_all(cases.iter().formatted())?), - ) - }, - &r_curly_token? - ) - .block_indent() - .finish()? + format_delimited(&l_curly_token?, &format_cases, &r_curly_token?).block_indent() ] ] } diff --git a/crates/rome_js_formatter/src/js/statements/throw_statement.rs b/crates/rome_js_formatter/src/js/statements/throw_statement.rs index 7c4add5f8b0..cb061fcc4e8 100644 --- a/crates/rome_js_formatter/src/js/statements/throw_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/throw_statement.rs @@ -1,15 +1,13 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use rome_formatter::{format_args, write}; +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; use rome_js_syntax::JsThrowStatement; use rome_js_syntax::JsThrowStatementFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsThrowStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsThrowStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsThrowStatementFields { throw_token, argument, @@ -19,10 +17,12 @@ impl FormatNodeFields for FormatNodeRule { let throw_token = throw_token.format(); let exception = argument.format(); - format_with_semicolon( - formatter, - formatted![formatter, [throw_token, space_token(), exception]]?, - semicolon_token, + write!( + f, + [FormatWithSemicolon::new( + &format_args!(throw_token, space_token(), exception), + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/js/statements/try_finally_statement.rs b/crates/rome_js_formatter/src/js/statements/try_finally_statement.rs index 2fb37edecb5..4f4f67945d7 100644 --- a/crates/rome_js_formatter/src/js/statements/try_finally_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/try_finally_statement.rs @@ -1,14 +1,12 @@ use crate::prelude::*; +use rome_formatter::write; use crate::FormatNodeFields; use rome_js_syntax::JsTryFinallyStatement; use rome_js_syntax::JsTryFinallyStatementFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsTryFinallyStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsTryFinallyStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsTryFinallyStatementFields { try_token, body, @@ -16,21 +14,12 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &JsTryStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsTryStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsTryStatementFields { try_token, body, catch_clause, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ try_token.format(), space_token(), diff --git a/crates/rome_js_formatter/src/js/statements/variable_statement.rs b/crates/rome_js_formatter/src/js/statements/variable_statement.rs index 86431546ccd..18988678b29 100644 --- a/crates/rome_js_formatter/src/js/statements/variable_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/variable_statement.rs @@ -1,24 +1,24 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use rome_formatter::write; +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; use rome_js_syntax::JsVariableStatement; use rome_js_syntax::JsVariableStatementFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsVariableStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsVariableStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsVariableStatementFields { declaration, semicolon_token, } = node.as_fields(); - format_with_semicolon( - formatter, - formatted![formatter, [declaration.format()]]?, - semicolon_token, + write!( + f, + [FormatWithSemicolon::new( + &declaration.format(), + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/js/statements/while_statement.rs b/crates/rome_js_formatter/src/js/statements/while_statement.rs index bdf9a7ce6a7..96ef7809189 100644 --- a/crates/rome_js_formatter/src/js/statements/while_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/while_statement.rs @@ -1,15 +1,13 @@ use crate::prelude::*; -use crate::utils::format_head_body_statement; +use crate::utils::FormatBodyStatement; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsWhileStatement; use rome_js_syntax::JsWhileStatementFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsWhileStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsWhileStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsWhileStatementFields { while_token, l_paren_token, @@ -18,24 +16,15 @@ impl FormatNodeFields for FormatNodeRule { body, } = node.as_fields(); - format_head_body_statement( - formatter, - formatted![ - formatter, - [ - while_token.format(), - space_token(), - formatter - .delimited( - &l_paren_token?, - formatted![formatter, [test.format()]]?, - &r_paren_token?, - ) - .soft_block_indent() - .finish()?, - ] - ]?, - body?, + write!( + f, + [ + while_token.format(), + space_token(), + format_delimited(&l_paren_token?, &test.format(), &r_paren_token?,) + .soft_block_indent(), + FormatBodyStatement::new(&body?) + ] ) } } diff --git a/crates/rome_js_formatter/src/js/statements/with_statement.rs b/crates/rome_js_formatter/src/js/statements/with_statement.rs index 74acd875701..3b83fa28797 100644 --- a/crates/rome_js_formatter/src/js/statements/with_statement.rs +++ b/crates/rome_js_formatter/src/js/statements/with_statement.rs @@ -1,15 +1,13 @@ use crate::prelude::*; -use crate::utils::format_head_body_statement; +use rome_formatter::write; +use crate::utils::FormatBodyStatement; use crate::FormatNodeFields; use rome_js_syntax::JsWithStatement; use rome_js_syntax::JsWithStatementFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsWithStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsWithStatement, f: &mut JsFormatter) -> FormatResult<()> { let JsWithStatementFields { with_token, l_paren_token, @@ -18,24 +16,15 @@ impl FormatNodeFields for FormatNodeRule { body, } = node.as_fields(); - format_head_body_statement( - formatter, - formatted![ - formatter, - [ - with_token.format(), - space_token(), - formatter - .delimited( - &l_paren_token?, - formatted![formatter, [object.format()]]?, - &r_paren_token?, - ) - .soft_block_indent() - .finish()?, - ] - ]?, - body?, + write!( + f, + [ + with_token.format(), + space_token(), + format_delimited(&l_paren_token?, &object.format(), &r_paren_token?,) + .soft_block_indent(), + FormatBodyStatement::new(&body?) + ] ) } } diff --git a/crates/rome_js_formatter/src/js/unknown/unknown.rs b/crates/rome_js_formatter/src/js/unknown/unknown.rs index 9bf277de4f3..ea78ccd76be 100644 --- a/crates/rome_js_formatter/src/js/unknown/unknown.rs +++ b/crates/rome_js_formatter/src/js/unknown/unknown.rs @@ -1,11 +1,10 @@ -use crate::formatter::unknown_node; use crate::prelude::*; use crate::FormatNodeFields; use rome_js_syntax::JsUnknown; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsUnknown, formatter: &JsFormatter) -> FormatResult { - unknown_node(node.syntax()).format(formatter) + fn fmt_fields(node: &JsUnknown, formatter: &mut JsFormatter) -> FormatResult<()> { + format_unknown_node(node.syntax()).fmt(formatter) } } diff --git a/crates/rome_js_formatter/src/js/unknown/unknown_assignment.rs b/crates/rome_js_formatter/src/js/unknown/unknown_assignment.rs index 5114f3eac51..f9fa2e8eb6c 100644 --- a/crates/rome_js_formatter/src/js/unknown/unknown_assignment.rs +++ b/crates/rome_js_formatter/src/js/unknown/unknown_assignment.rs @@ -1,14 +1,10 @@ -use crate::formatter::verbatim_node; use crate::prelude::*; use crate::FormatNodeFields; use rome_js_syntax::JsUnknownAssignment; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsUnknownAssignment, - formatter: &JsFormatter, - ) -> FormatResult { - verbatim_node(node.syntax()).format(formatter) + fn fmt_fields(node: &JsUnknownAssignment, formatter: &mut JsFormatter) -> FormatResult<()> { + format_unknown_node(node.syntax()).fmt(formatter) } } diff --git a/crates/rome_js_formatter/src/js/unknown/unknown_binding.rs b/crates/rome_js_formatter/src/js/unknown/unknown_binding.rs index cb2e6fcc401..f56b3cdd145 100644 --- a/crates/rome_js_formatter/src/js/unknown/unknown_binding.rs +++ b/crates/rome_js_formatter/src/js/unknown/unknown_binding.rs @@ -1,15 +1,11 @@ use crate::prelude::*; -use crate::formatter::unknown_node; use crate::FormatNodeFields; use rome_js_syntax::JsUnknownBinding; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsUnknownBinding, - formatter: &JsFormatter, - ) -> FormatResult { - unknown_node(node.syntax()).format(formatter) + fn fmt_fields(node: &JsUnknownBinding, formatter: &mut JsFormatter) -> FormatResult<()> { + format_unknown_node(node.syntax()).fmt(formatter) } } diff --git a/crates/rome_js_formatter/src/js/unknown/unknown_expression.rs b/crates/rome_js_formatter/src/js/unknown/unknown_expression.rs index 6f600fb0093..ba7e21aa20a 100644 --- a/crates/rome_js_formatter/src/js/unknown/unknown_expression.rs +++ b/crates/rome_js_formatter/src/js/unknown/unknown_expression.rs @@ -1,15 +1,11 @@ use crate::prelude::*; -use crate::formatter::unknown_node; use crate::FormatNodeFields; use rome_js_syntax::JsUnknownExpression; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsUnknownExpression, - formatter: &JsFormatter, - ) -> FormatResult { - unknown_node(node.syntax()).format(formatter) + fn fmt_fields(node: &JsUnknownExpression, formatter: &mut JsFormatter) -> FormatResult<()> { + format_unknown_node(node.syntax()).fmt(formatter) } } diff --git a/crates/rome_js_formatter/src/js/unknown/unknown_import_assertion_entry.rs b/crates/rome_js_formatter/src/js/unknown/unknown_import_assertion_entry.rs index 2727d894539..e99c7d7c275 100644 --- a/crates/rome_js_formatter/src/js/unknown/unknown_import_assertion_entry.rs +++ b/crates/rome_js_formatter/src/js/unknown/unknown_import_assertion_entry.rs @@ -1,6 +1,5 @@ use crate::prelude::*; -use crate::formatter::unknown_node; use crate::FormatNodeFields; use rome_js_syntax::JsUnknownImportAssertionEntry; use rome_rowan::AstNode; @@ -8,10 +7,10 @@ use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields( + fn fmt_fields( node: &JsUnknownImportAssertionEntry, - formatter: &JsFormatter, - ) -> FormatResult { - unknown_node(node.syntax()).format(formatter) + formatter: &mut JsFormatter, + ) -> FormatResult<()> { + format_unknown_node(node.syntax()).fmt(formatter) } } diff --git a/crates/rome_js_formatter/src/js/unknown/unknown_member.rs b/crates/rome_js_formatter/src/js/unknown/unknown_member.rs index 53e55dbcf54..c2fe342bd73 100644 --- a/crates/rome_js_formatter/src/js/unknown/unknown_member.rs +++ b/crates/rome_js_formatter/src/js/unknown/unknown_member.rs @@ -1,15 +1,11 @@ use crate::prelude::*; -use crate::formatter::unknown_node; use crate::FormatNodeFields; use rome_js_syntax::JsUnknownMember; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsUnknownMember, - formatter: &JsFormatter, - ) -> FormatResult { - unknown_node(node.syntax()).format(formatter) + fn fmt_fields(node: &JsUnknownMember, formatter: &mut JsFormatter) -> FormatResult<()> { + format_unknown_node(node.syntax()).fmt(formatter) } } diff --git a/crates/rome_js_formatter/src/js/unknown/unknown_named_import_specifier.rs b/crates/rome_js_formatter/src/js/unknown/unknown_named_import_specifier.rs index 3cb79da2e7b..476cff2c0bd 100644 --- a/crates/rome_js_formatter/src/js/unknown/unknown_named_import_specifier.rs +++ b/crates/rome_js_formatter/src/js/unknown/unknown_named_import_specifier.rs @@ -1,6 +1,5 @@ use crate::prelude::*; -use crate::formatter::unknown_node; use crate::FormatNodeFields; use rome_js_syntax::JsUnknownNamedImportSpecifier; use rome_rowan::AstNode; @@ -8,10 +7,10 @@ use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields( + fn fmt_fields( node: &JsUnknownNamedImportSpecifier, - formatter: &JsFormatter, - ) -> FormatResult { - unknown_node(node.syntax()).format(formatter) + formatter: &mut JsFormatter, + ) -> FormatResult<()> { + format_unknown_node(node.syntax()).fmt(formatter) } } diff --git a/crates/rome_js_formatter/src/js/unknown/unknown_parameter.rs b/crates/rome_js_formatter/src/js/unknown/unknown_parameter.rs index 54740420ec8..0ab6e6af5e2 100644 --- a/crates/rome_js_formatter/src/js/unknown/unknown_parameter.rs +++ b/crates/rome_js_formatter/src/js/unknown/unknown_parameter.rs @@ -1,15 +1,11 @@ use crate::prelude::*; -use crate::formatter::unknown_node; use crate::FormatNodeFields; use rome_js_syntax::JsUnknownParameter; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsUnknownParameter, - formatter: &JsFormatter, - ) -> FormatResult { - unknown_node(node.syntax()).format(formatter) + fn fmt_fields(node: &JsUnknownParameter, formatter: &mut JsFormatter) -> FormatResult<()> { + format_unknown_node(node.syntax()).fmt(formatter) } } diff --git a/crates/rome_js_formatter/src/js/unknown/unknown_statement.rs b/crates/rome_js_formatter/src/js/unknown/unknown_statement.rs index 75230cdf800..77596cf90c8 100644 --- a/crates/rome_js_formatter/src/js/unknown/unknown_statement.rs +++ b/crates/rome_js_formatter/src/js/unknown/unknown_statement.rs @@ -1,15 +1,11 @@ use crate::prelude::*; -use crate::formatter::unknown_node; use crate::FormatNodeFields; use rome_js_syntax::JsUnknownStatement; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsUnknownStatement, - formatter: &JsFormatter, - ) -> FormatResult { - unknown_node(node.syntax()).format(formatter) + fn fmt_fields(node: &JsUnknownStatement, formatter: &mut JsFormatter) -> FormatResult<()> { + format_unknown_node(node.syntax()).fmt(formatter) } } diff --git a/crates/rome_js_formatter/src/jsx/any/attribute.rs b/crates/rome_js_formatter/src/jsx/any/attribute.rs index 4b06181502d..1bc2726a6a0 100644 --- a/crates/rome_js_formatter/src/jsx/any/attribute.rs +++ b/crates/rome_js_formatter/src/jsx/any/attribute.rs @@ -5,10 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsxAnyAttribute; impl FormatRule for FormatJsxAnyAttribute { type Context = JsFormatContext; - fn format(node: &JsxAnyAttribute, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsxAnyAttribute, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsxAnyAttribute::JsxAttribute(node) => formatted![formatter, [node.format()]], - JsxAnyAttribute::JsxSpreadAttribute(node) => formatted![formatter, [node.format()]], + JsxAnyAttribute::JsxAttribute(node) => node.format().fmt(f), + JsxAnyAttribute::JsxSpreadAttribute(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/jsx/any/attribute_name.rs b/crates/rome_js_formatter/src/jsx/any/attribute_name.rs index 3be92016ec3..13606a65df2 100644 --- a/crates/rome_js_formatter/src/jsx/any/attribute_name.rs +++ b/crates/rome_js_formatter/src/jsx/any/attribute_name.rs @@ -5,10 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsxAnyAttributeName; impl FormatRule for FormatJsxAnyAttributeName { type Context = JsFormatContext; - fn format(node: &JsxAnyAttributeName, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsxAnyAttributeName, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsxAnyAttributeName::JsxName(node) => formatted![formatter, [node.format()]], - JsxAnyAttributeName::JsxNamespaceName(node) => formatted![formatter, [node.format()]], + JsxAnyAttributeName::JsxName(node) => node.format().fmt(f), + JsxAnyAttributeName::JsxNamespaceName(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/jsx/any/attribute_value.rs b/crates/rome_js_formatter/src/jsx/any/attribute_value.rs index 10907a393e3..0bede1f2d85 100644 --- a/crates/rome_js_formatter/src/jsx/any/attribute_value.rs +++ b/crates/rome_js_formatter/src/jsx/any/attribute_value.rs @@ -5,13 +5,11 @@ use crate::prelude::*; use rome_js_syntax::JsxAnyAttributeValue; impl FormatRule for FormatJsxAnyAttributeValue { type Context = JsFormatContext; - fn format(node: &JsxAnyAttributeValue, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsxAnyAttributeValue, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsxAnyAttributeValue::JsxAnyTag(node) => formatted![formatter, [node.format()]], - JsxAnyAttributeValue::JsxString(node) => formatted![formatter, [node.format()]], - JsxAnyAttributeValue::JsxExpressionAttributeValue(node) => { - formatted![formatter, [node.format()]] - } + JsxAnyAttributeValue::JsxAnyTag(node) => node.format().fmt(f), + JsxAnyAttributeValue::JsxString(node) => node.format().fmt(f), + JsxAnyAttributeValue::JsxExpressionAttributeValue(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/jsx/any/child.rs b/crates/rome_js_formatter/src/jsx/any/child.rs index 69585692b21..1be4d22cc56 100644 --- a/crates/rome_js_formatter/src/jsx/any/child.rs +++ b/crates/rome_js_formatter/src/jsx/any/child.rs @@ -5,14 +5,14 @@ use crate::prelude::*; use rome_js_syntax::JsxAnyChild; impl FormatRule for FormatJsxAnyChild { type Context = JsFormatContext; - fn format(node: &JsxAnyChild, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsxAnyChild, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsxAnyChild::JsxElement(node) => formatted![formatter, [node.format()]], - JsxAnyChild::JsxSelfClosingElement(node) => formatted![formatter, [node.format()]], - JsxAnyChild::JsxText(node) => formatted![formatter, [node.format()]], - JsxAnyChild::JsxExpressionChild(node) => formatted![formatter, [node.format()]], - JsxAnyChild::JsxSpreadChild(node) => formatted![formatter, [node.format()]], - JsxAnyChild::JsxFragment(node) => formatted![formatter, [node.format()]], + JsxAnyChild::JsxElement(node) => node.format().fmt(f), + JsxAnyChild::JsxSelfClosingElement(node) => node.format().fmt(f), + JsxAnyChild::JsxText(node) => node.format().fmt(f), + JsxAnyChild::JsxExpressionChild(node) => node.format().fmt(f), + JsxAnyChild::JsxSpreadChild(node) => node.format().fmt(f), + JsxAnyChild::JsxFragment(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/jsx/any/element_name.rs b/crates/rome_js_formatter/src/jsx/any/element_name.rs index 074e1ec59e5..c40674d3121 100644 --- a/crates/rome_js_formatter/src/jsx/any/element_name.rs +++ b/crates/rome_js_formatter/src/jsx/any/element_name.rs @@ -5,14 +5,12 @@ use crate::prelude::*; use rome_js_syntax::JsxAnyElementName; impl FormatRule for FormatJsxAnyElementName { type Context = JsFormatContext; - fn format(node: &JsxAnyElementName, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsxAnyElementName, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsxAnyElementName::JsxName(node) => formatted![formatter, [node.format()]], - JsxAnyElementName::JsxReferenceIdentifier(node) => { - formatted![formatter, [node.format()]] - } - JsxAnyElementName::JsxMemberName(node) => formatted![formatter, [node.format()]], - JsxAnyElementName::JsxNamespaceName(node) => formatted![formatter, [node.format()]], + JsxAnyElementName::JsxName(node) => node.format().fmt(f), + JsxAnyElementName::JsxReferenceIdentifier(node) => node.format().fmt(f), + JsxAnyElementName::JsxMemberName(node) => node.format().fmt(f), + JsxAnyElementName::JsxNamespaceName(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/jsx/any/name.rs b/crates/rome_js_formatter/src/jsx/any/name.rs index abc34a691af..33c310c4fc8 100644 --- a/crates/rome_js_formatter/src/jsx/any/name.rs +++ b/crates/rome_js_formatter/src/jsx/any/name.rs @@ -5,10 +5,10 @@ use crate::prelude::*; use rome_js_syntax::JsxAnyName; impl FormatRule for FormatJsxAnyName { type Context = JsFormatContext; - fn format(node: &JsxAnyName, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsxAnyName, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsxAnyName::JsxName(node) => formatted![formatter, [node.format()]], - JsxAnyName::JsxNamespaceName(node) => formatted![formatter, [node.format()]], + JsxAnyName::JsxName(node) => node.format().fmt(f), + JsxAnyName::JsxNamespaceName(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/jsx/any/object_name.rs b/crates/rome_js_formatter/src/jsx/any/object_name.rs index ae6437478f0..740d219945b 100644 --- a/crates/rome_js_formatter/src/jsx/any/object_name.rs +++ b/crates/rome_js_formatter/src/jsx/any/object_name.rs @@ -5,13 +5,11 @@ use crate::prelude::*; use rome_js_syntax::JsxAnyObjectName; impl FormatRule for FormatJsxAnyObjectName { type Context = JsFormatContext; - fn format(node: &JsxAnyObjectName, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsxAnyObjectName, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsxAnyObjectName::JsxReferenceIdentifier(node) => { - formatted![formatter, [node.format()]] - } - JsxAnyObjectName::JsxMemberName(node) => formatted![formatter, [node.format()]], - JsxAnyObjectName::JsxNamespaceName(node) => formatted![formatter, [node.format()]], + JsxAnyObjectName::JsxReferenceIdentifier(node) => node.format().fmt(f), + JsxAnyObjectName::JsxMemberName(node) => node.format().fmt(f), + JsxAnyObjectName::JsxNamespaceName(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/jsx/any/tag.rs b/crates/rome_js_formatter/src/jsx/any/tag.rs index 20a8412811f..1c346ae0a1c 100644 --- a/crates/rome_js_formatter/src/jsx/any/tag.rs +++ b/crates/rome_js_formatter/src/jsx/any/tag.rs @@ -5,11 +5,11 @@ use crate::prelude::*; use rome_js_syntax::JsxAnyTag; impl FormatRule for FormatJsxAnyTag { type Context = JsFormatContext; - fn format(node: &JsxAnyTag, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &JsxAnyTag, f: &mut JsFormatter) -> FormatResult<()> { match node { - JsxAnyTag::JsxElement(node) => formatted![formatter, [node.format()]], - JsxAnyTag::JsxSelfClosingElement(node) => formatted![formatter, [node.format()]], - JsxAnyTag::JsxFragment(node) => formatted![formatter, [node.format()]], + JsxAnyTag::JsxElement(node) => node.format().fmt(f), + JsxAnyTag::JsxSelfClosingElement(node) => node.format().fmt(f), + JsxAnyTag::JsxFragment(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/jsx/attribute/attribute.rs b/crates/rome_js_formatter/src/jsx/attribute/attribute.rs index a6fbf43e13a..5af0f5a5637 100644 --- a/crates/rome_js_formatter/src/jsx/attribute/attribute.rs +++ b/crates/rome_js_formatter/src/jsx/attribute/attribute.rs @@ -1,11 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{JsxAttribute, JsxAttributeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsxAttribute, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &JsxAttribute, f: &mut JsFormatter) -> FormatResult<()> { let JsxAttributeFields { name, initializer } = node.as_fields(); - formatted![formatter, [name.format(), initializer.format()]] + write![f, [name.format(), initializer.format()]] } } diff --git a/crates/rome_js_formatter/src/jsx/attribute/attribute_initializer_clause.rs b/crates/rome_js_formatter/src/jsx/attribute/attribute_initializer_clause.rs index 85023d5e416..08c3240d79e 100644 --- a/crates/rome_js_formatter/src/jsx/attribute/attribute_initializer_clause.rs +++ b/crates/rome_js_formatter/src/jsx/attribute/attribute_initializer_clause.rs @@ -1,16 +1,14 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{JsxAttributeInitializerClause, JsxAttributeInitializerClauseFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsxAttributeInitializerClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsxAttributeInitializerClause, f: &mut JsFormatter) -> FormatResult<()> { let JsxAttributeInitializerClauseFields { eq_token, value } = node.as_fields(); - formatted![formatter, [eq_token.format(), value.format()]] + write![f, [eq_token.format(), value.format()]] } } diff --git a/crates/rome_js_formatter/src/jsx/attribute/expression_attribute_value.rs b/crates/rome_js_formatter/src/jsx/attribute/expression_attribute_value.rs index b9725080fec..d332f18abe8 100644 --- a/crates/rome_js_formatter/src/jsx/attribute/expression_attribute_value.rs +++ b/crates/rome_js_formatter/src/jsx/attribute/expression_attribute_value.rs @@ -1,72 +1,69 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{ JsAnyExpression, JsxExpressionAttributeValue, JsxExpressionAttributeValueFields, }; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsxExpressionAttributeValue, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsxExpressionAttributeValue, f: &mut JsFormatter) -> FormatResult<()> { let JsxExpressionAttributeValueFields { l_curly_token, expression, r_curly_token, } = node.as_fields(); - let expression = expression?; + write!( + f, + [group_elements(&format_with(|f| { + write!(f, [l_curly_token.format()])?; - // When the inner expression for a prop is an object, array, or call expression, we want to combine the - // delimiters of the expression (`{`, `}`, `[`, `]`, or `(`, `)`) with the delimiters of the JSX - // attribute (`{`, `}`), so that we don't end up with redundant indents. Therefore we do not - // soft indent the expression - // - // Good: - // ```jsx - // - // ``` - // - // Bad: - // ```jsx - // - // ``` - // - let formatted_expression = if matches!( - expression, - JsAnyExpression::JsObjectExpression(_) - | JsAnyExpression::JsArrayExpression(_) - | JsAnyExpression::JsCallExpression(_) - ) { - formatted![formatter, [expression.format()]]? - } else { - soft_block_indent(formatted![formatter, [expression.format()]]?) - }; + let expression = expression.as_ref()?; + + // When the inner expression for a prop is an object, array, or call expression, we want to combine the + // delimiters of the expression (`{`, `}`, `[`, `]`, or `(`, `)`) with the delimiters of the JSX + // attribute (`{`, `}`), so that we don't end up with redundant indents. Therefore we do not + // soft indent the expression + // + // Good: + // ```jsx + // + // ``` + // + // Bad: + // ```jsx + // + // ``` + // + if matches!( + expression, + JsAnyExpression::JsObjectExpression(_) + | JsAnyExpression::JsArrayExpression(_) + | JsAnyExpression::JsCallExpression(_) + ) { + write!(f, [expression.format()])?; + } else { + write!(f, [soft_block_indent(&expression.format())])?; + }; - Ok(group_elements(formatted![ - formatter, - [ - l_curly_token.format(), - formatted_expression, - line_suffix_boundary(), - r_curly_token.format(), - ] - ]?)) + write!(f, [line_suffix_boundary(), r_curly_token.format()]) + }))] + ) } } diff --git a/crates/rome_js_formatter/src/jsx/attribute/spread_attribute.rs b/crates/rome_js_formatter/src/jsx/attribute/spread_attribute.rs index c5f7658ac63..94f0db10b95 100644 --- a/crates/rome_js_formatter/src/jsx/attribute/spread_attribute.rs +++ b/crates/rome_js_formatter/src/jsx/attribute/spread_attribute.rs @@ -1,12 +1,10 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{JsxSpreadAttribute, JsxSpreadAttributeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsxSpreadAttribute, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsxSpreadAttribute, f: &mut JsFormatter) -> FormatResult<()> { let JsxSpreadAttributeFields { l_curly_token, dotdotdot_token, @@ -14,8 +12,8 @@ impl FormatNodeFields for FormatNodeRule r_curly_token, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ l_curly_token.format(), dotdotdot_token.format(), diff --git a/crates/rome_js_formatter/src/jsx/auxiliary/expression_child.rs b/crates/rome_js_formatter/src/jsx/auxiliary/expression_child.rs index ddc80bf66a4..33cbb8a4069 100644 --- a/crates/rome_js_formatter/src/jsx/auxiliary/expression_child.rs +++ b/crates/rome_js_formatter/src/jsx/auxiliary/expression_child.rs @@ -1,14 +1,10 @@ -use crate::formatter::verbatim_node; use crate::prelude::*; use crate::FormatNodeFields; use rome_js_syntax::JsxExpressionChild; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsxExpressionChild, - formatter: &JsFormatter, - ) -> FormatResult { - verbatim_node(node.syntax()).format(formatter) + fn fmt_fields(node: &JsxExpressionChild, formatter: &mut JsFormatter) -> FormatResult<()> { + format_verbatim_node(node.syntax()).fmt(formatter) } } diff --git a/crates/rome_js_formatter/src/jsx/auxiliary/name.rs b/crates/rome_js_formatter/src/jsx/auxiliary/name.rs index 941d97d825c..f135ef7e14a 100644 --- a/crates/rome_js_formatter/src/jsx/auxiliary/name.rs +++ b/crates/rome_js_formatter/src/jsx/auxiliary/name.rs @@ -1,11 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{JsxName, JsxNameFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsxName, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &JsxName, f: &mut JsFormatter) -> FormatResult<()> { let JsxNameFields { value_token } = node.as_fields(); - formatted![formatter, [value_token.format()]] + write![f, [value_token.format()]] } } diff --git a/crates/rome_js_formatter/src/jsx/auxiliary/namespace_name.rs b/crates/rome_js_formatter/src/jsx/auxiliary/namespace_name.rs index 95d013a508f..c3da901ba55 100644 --- a/crates/rome_js_formatter/src/jsx/auxiliary/namespace_name.rs +++ b/crates/rome_js_formatter/src/jsx/auxiliary/namespace_name.rs @@ -1,21 +1,16 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{JsxNamespaceName, JsxNamespaceNameFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsxNamespaceName, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsxNamespaceName, f: &mut JsFormatter) -> FormatResult<()> { let JsxNamespaceNameFields { namespace, colon_token, name, } = node.as_fields(); - formatted![ - formatter, - [namespace.format(), colon_token.format(), name.format()] - ] + write![f, [namespace.format(), colon_token.format(), name.format()]] } } diff --git a/crates/rome_js_formatter/src/jsx/auxiliary/reference_identifier.rs b/crates/rome_js_formatter/src/jsx/auxiliary/reference_identifier.rs index 284c2b80cde..80a3c483222 100644 --- a/crates/rome_js_formatter/src/jsx/auxiliary/reference_identifier.rs +++ b/crates/rome_js_formatter/src/jsx/auxiliary/reference_identifier.rs @@ -1,12 +1,10 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsxReferenceIdentifier; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsxReferenceIdentifier, - formatter: &JsFormatter, - ) -> FormatResult { - formatted![formatter, [node.value_token().format()]] + fn fmt_fields(node: &JsxReferenceIdentifier, f: &mut JsFormatter) -> FormatResult<()> { + write![f, [node.value_token().format()]] } } diff --git a/crates/rome_js_formatter/src/jsx/auxiliary/spread_child.rs b/crates/rome_js_formatter/src/jsx/auxiliary/spread_child.rs index f8862914796..fe3b3508eb9 100644 --- a/crates/rome_js_formatter/src/jsx/auxiliary/spread_child.rs +++ b/crates/rome_js_formatter/src/jsx/auxiliary/spread_child.rs @@ -1,14 +1,10 @@ -use crate::formatter::verbatim_node; use crate::prelude::*; use crate::FormatNodeFields; use rome_js_syntax::JsxSpreadChild; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsxSpreadChild, - formatter: &JsFormatter, - ) -> FormatResult { - verbatim_node(node.syntax()).format(formatter) + fn fmt_fields(node: &JsxSpreadChild, formatter: &mut JsFormatter) -> FormatResult<()> { + format_verbatim_node(node.syntax()).fmt(formatter) } } diff --git a/crates/rome_js_formatter/src/jsx/auxiliary/string.rs b/crates/rome_js_formatter/src/jsx/auxiliary/string.rs index 1fbef61a1f0..f3dc7b7b9b1 100644 --- a/crates/rome_js_formatter/src/jsx/auxiliary/string.rs +++ b/crates/rome_js_formatter/src/jsx/auxiliary/string.rs @@ -1,9 +1,10 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsxString; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsxString, formatter: &JsFormatter) -> FormatResult { - formatted![formatter, [node.value_token().format()]] + fn fmt_fields(node: &JsxString, f: &mut JsFormatter) -> FormatResult<()> { + write![f, [node.value_token().format()]] } } diff --git a/crates/rome_js_formatter/src/jsx/auxiliary/text.rs b/crates/rome_js_formatter/src/jsx/auxiliary/text.rs index eee848d0c70..7ff1511b29d 100644 --- a/crates/rome_js_formatter/src/jsx/auxiliary/text.rs +++ b/crates/rome_js_formatter/src/jsx/auxiliary/text.rs @@ -1,19 +1,26 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{JsxText, JsxTextFields}; use std::borrow::Cow; + use std::ops::Range; use std::str::CharIndices; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsxText, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &JsxText, f: &mut JsFormatter) -> FormatResult<()> { let JsxTextFields { value_token } = node.as_fields(); let token = value_token?; let new_text = clean_jsx_text(token.text()); let start = token.text_range().start(); - let new_token = Token::from_syntax_token_cow_slice(new_text, &token, start); - Ok(formatter.format_replaced(&token, FormatElement::from(new_token))) + write!( + f, + [format_replaced( + &token, + &syntax_token_cow_slice(new_text, &token, start) + )] + ) } } @@ -175,10 +182,10 @@ fn get_trimmed_text( (Some(WhitespaceType::HasNewline), None) => Cow::Borrowed(text.trim_start()), (None, Some(WhitespaceType::HasNewline)) => Cow::Borrowed(text.trim_end()), (Some(WhitespaceType::NoNewline), Some(WhitespaceType::NoNewline)) => { - Cow::Owned(format!(" {} ", text.trim())) + Cow::Owned(std::format!(" {} ", text.trim())) } - (Some(WhitespaceType::NoNewline), _) => Cow::Owned(format!(" {}", text.trim())), - (_, Some(WhitespaceType::NoNewline)) => Cow::Owned(format!("{} ", text.trim())), + (Some(WhitespaceType::NoNewline), _) => Cow::Owned(std::format!(" {}", text.trim())), + (_, Some(WhitespaceType::NoNewline)) => Cow::Owned(std::format!("{} ", text.trim())), } } diff --git a/crates/rome_js_formatter/src/jsx/expressions/tag_expression.rs b/crates/rome_js_formatter/src/jsx/expressions/tag_expression.rs index 956bde79b09..43a5f0bb360 100644 --- a/crates/rome_js_formatter/src/jsx/expressions/tag_expression.rs +++ b/crates/rome_js_formatter/src/jsx/expressions/tag_expression.rs @@ -1,12 +1,10 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::JsxTagExpression; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsxTagExpression, - formatter: &JsFormatter, - ) -> FormatResult { - formatted![formatter, [node.tag().format()]] + fn fmt_fields(node: &JsxTagExpression, f: &mut JsFormatter) -> FormatResult<()> { + write![f, [node.tag().format()]] } } diff --git a/crates/rome_js_formatter/src/jsx/lists/attribute_list.rs b/crates/rome_js_formatter/src/jsx/lists/attribute_list.rs index 02b850c0e4f..09e544cc28f 100644 --- a/crates/rome_js_formatter/src/jsx/lists/attribute_list.rs +++ b/crates/rome_js_formatter/src/jsx/lists/attribute_list.rs @@ -1,16 +1,18 @@ use crate::generated::FormatJsxAttributeList; use crate::prelude::*; +use rome_formatter::write; use rome_js_syntax::JsxAttributeList; impl FormatRule for FormatJsxAttributeList { type Context = JsFormatContext; - fn format(node: &JsxAttributeList, formatter: &JsFormatter) -> FormatResult { - let attributes = join_elements( - soft_line_break_or_space(), - formatter.format_all(node.iter().formatted())?, - ); + fn fmt(node: &JsxAttributeList, f: &mut JsFormatter) -> FormatResult<()> { + let attributes = format_with(|f| { + f.join_with(&soft_line_break_or_space()) + .entries(node.iter().formatted()) + .finish() + }); - Ok(group_elements(soft_block_indent(attributes))) + write!(f, [group_elements(&soft_block_indent(&attributes))]) } } diff --git a/crates/rome_js_formatter/src/jsx/lists/child_list.rs b/crates/rome_js_formatter/src/jsx/lists/child_list.rs index 622ba1df988..a3fc7fc0f32 100644 --- a/crates/rome_js_formatter/src/jsx/lists/child_list.rs +++ b/crates/rome_js_formatter/src/jsx/lists/child_list.rs @@ -1,4 +1,3 @@ -use crate::formatter::verbatim_node; use crate::generated::FormatJsxChildList; use crate::prelude::*; use rome_js_syntax::JsxChildList; @@ -7,7 +6,7 @@ use rome_rowan::AstNode; impl FormatRule for FormatJsxChildList { type Context = JsFormatContext; - fn format(node: &JsxChildList, formatter: &JsFormatter) -> FormatResult { - verbatim_node(node.syntax()).format(formatter) + fn fmt(node: &JsxChildList, formatter: &mut JsFormatter) -> FormatResult<()> { + format_verbatim_node(node.syntax()).fmt(formatter) } } diff --git a/crates/rome_js_formatter/src/jsx/objects/member_name.rs b/crates/rome_js_formatter/src/jsx/objects/member_name.rs index 6dd25c95ea3..2e64469ccd9 100644 --- a/crates/rome_js_formatter/src/jsx/objects/member_name.rs +++ b/crates/rome_js_formatter/src/jsx/objects/member_name.rs @@ -1,18 +1,16 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{JsxMemberName, JsxMemberNameFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsxMemberName, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &JsxMemberName, f: &mut JsFormatter) -> FormatResult<()> { let JsxMemberNameFields { object, dot_token, member, } = node.as_fields(); - formatted![ - formatter, - [object.format(), dot_token.format(), member.format(),] - ] + write![f, [object.format(), dot_token.format(), member.format(),]] } } diff --git a/crates/rome_js_formatter/src/jsx/tag/closing_element.rs b/crates/rome_js_formatter/src/jsx/tag/closing_element.rs index 5cd4148f85c..786f5aa0966 100644 --- a/crates/rome_js_formatter/src/jsx/tag/closing_element.rs +++ b/crates/rome_js_formatter/src/jsx/tag/closing_element.rs @@ -1,14 +1,10 @@ -use crate::formatter::verbatim_node; use crate::prelude::*; use crate::FormatNodeFields; use rome_js_syntax::JsxClosingElement; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsxClosingElement, - formatter: &JsFormatter, - ) -> FormatResult { - verbatim_node(node.syntax()).format(formatter) + fn fmt_fields(node: &JsxClosingElement, formatter: &mut JsFormatter) -> FormatResult<()> { + format_verbatim_node(node.syntax()).fmt(formatter) } } diff --git a/crates/rome_js_formatter/src/jsx/tag/closing_fragment.rs b/crates/rome_js_formatter/src/jsx/tag/closing_fragment.rs index f9ca216d08d..1be3067b786 100644 --- a/crates/rome_js_formatter/src/jsx/tag/closing_fragment.rs +++ b/crates/rome_js_formatter/src/jsx/tag/closing_fragment.rs @@ -1,20 +1,18 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{JsxClosingFragment, JsxClosingFragmentFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsxClosingFragment, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsxClosingFragment, f: &mut JsFormatter) -> FormatResult<()> { let JsxClosingFragmentFields { r_angle_token, slash_token, l_angle_token, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ l_angle_token.format(), slash_token.format(), diff --git a/crates/rome_js_formatter/src/jsx/tag/element.rs b/crates/rome_js_formatter/src/jsx/tag/element.rs index c9cc333b1f1..0233f872758 100644 --- a/crates/rome_js_formatter/src/jsx/tag/element.rs +++ b/crates/rome_js_formatter/src/jsx/tag/element.rs @@ -1,11 +1,10 @@ -use crate::formatter::verbatim_node; use crate::prelude::*; use crate::FormatNodeFields; use rome_js_syntax::JsxElement; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsxElement, formatter: &JsFormatter) -> FormatResult { - verbatim_node(node.syntax()).format(formatter) + fn fmt_fields(node: &JsxElement, formatter: &mut JsFormatter) -> FormatResult<()> { + format_verbatim_node(node.syntax()).fmt(formatter) } } diff --git a/crates/rome_js_formatter/src/jsx/tag/fragment.rs b/crates/rome_js_formatter/src/jsx/tag/fragment.rs index b1aff3153bf..7a437722807 100644 --- a/crates/rome_js_formatter/src/jsx/tag/fragment.rs +++ b/crates/rome_js_formatter/src/jsx/tag/fragment.rs @@ -1,17 +1,18 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{JsxFragment, JsxFragmentFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &JsxFragment, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &JsxFragment, f: &mut JsFormatter) -> FormatResult<()> { let JsxFragmentFields { opening_fragment, children, closing_fragment, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ opening_fragment.format(), children.format(), diff --git a/crates/rome_js_formatter/src/jsx/tag/opening_element.rs b/crates/rome_js_formatter/src/jsx/tag/opening_element.rs index dfa35aad799..d5150eefcfd 100644 --- a/crates/rome_js_formatter/src/jsx/tag/opening_element.rs +++ b/crates/rome_js_formatter/src/jsx/tag/opening_element.rs @@ -1,14 +1,10 @@ -use crate::formatter::verbatim_node; use crate::prelude::*; use crate::FormatNodeFields; use rome_js_syntax::JsxOpeningElement; use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsxOpeningElement, - formatter: &JsFormatter, - ) -> FormatResult { - verbatim_node(node.syntax()).format(formatter) + fn fmt_fields(node: &JsxOpeningElement, formatter: &mut JsFormatter) -> FormatResult<()> { + format_verbatim_node(node.syntax()).fmt(formatter) } } diff --git a/crates/rome_js_formatter/src/jsx/tag/opening_fragment.rs b/crates/rome_js_formatter/src/jsx/tag/opening_fragment.rs index b5c313ee54d..241bea427ef 100644 --- a/crates/rome_js_formatter/src/jsx/tag/opening_fragment.rs +++ b/crates/rome_js_formatter/src/jsx/tag/opening_fragment.rs @@ -1,17 +1,15 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{JsxOpeningFragment, JsxOpeningFragmentFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsxOpeningFragment, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsxOpeningFragment, f: &mut JsFormatter) -> FormatResult<()> { let JsxOpeningFragmentFields { r_angle_token, l_angle_token, } = node.as_fields(); - formatted![formatter, [l_angle_token.format(), r_angle_token.format()]] + write![f, [l_angle_token.format(), r_angle_token.format()]] } } diff --git a/crates/rome_js_formatter/src/jsx/tag/self_closing_element.rs b/crates/rome_js_formatter/src/jsx/tag/self_closing_element.rs index fd8b3e1cac9..b7b195ba785 100644 --- a/crates/rome_js_formatter/src/jsx/tag/self_closing_element.rs +++ b/crates/rome_js_formatter/src/jsx/tag/self_closing_element.rs @@ -1,12 +1,10 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{JsxSelfClosingElement, JsxSelfClosingElementFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &JsxSelfClosingElement, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &JsxSelfClosingElement, f: &mut JsFormatter) -> FormatResult<()> { let JsxSelfClosingElementFields { l_angle_token, name, @@ -16,8 +14,8 @@ impl FormatNodeFields for FormatNodeRule = Formatter<'buf, JsFormatContext>; + // Per Crate /// Used to get an object that knows how to format this object. pub trait AsFormat<'a> { - type Format: Format; + type Format: Format; /// Returns an object that is able to format this object. fn format(&'a self) -> Self::Format; @@ -83,15 +85,15 @@ where /// Used to convert this object into an object that can be formatted. /// /// The difference to [AsFormat] is that this trait takes ownership of `self`. -pub trait IntoFormat { - type Format: Format; +pub trait IntoFormat { + type Format: Format; fn into_format(self) -> Self::Format; } -impl IntoFormat for SyntaxResult +impl IntoFormat for SyntaxResult where - T: IntoFormat, + T: IntoFormat, { type Format = SyntaxResult; @@ -103,9 +105,9 @@ where /// Implement [IntoFormat] for [Option] when `T` implements [IntoFormat] /// /// Allows to call format on optional AST fields without having to unwrap the field first. -impl IntoFormat for Option +impl IntoFormat for Option where - T: IntoFormat, + T: IntoFormat, { type Format = Option; @@ -117,28 +119,32 @@ where /// Formatting specific [Iterator] extensions pub trait FormattedIterExt { /// Converts every item to an object that knows how to format it. - fn formatted(self) -> FormattedIter + fn formatted(self) -> FormattedIter where Self: Iterator + Sized, - Self::Item: IntoFormat, + Self::Item: IntoFormat, { - FormattedIter { inner: self } + FormattedIter { + inner: self, + options: PhantomData, + } } } impl FormattedIterExt for I where I: Iterator {} -pub struct FormattedIter +pub struct FormattedIter where Iter: Iterator, { inner: Iter, + options: PhantomData, } -impl Iterator for FormattedIter +impl Iterator for FormattedIter where Iter: Iterator, - Item: IntoFormat, + Item: IntoFormat, { type Item = Item::Format; @@ -147,17 +153,17 @@ where } } -impl FusedIterator for FormattedIter +impl FusedIterator for FormattedIter where Iter: FusedIterator, - Item: IntoFormat, + Item: IntoFormat, { } -impl ExactSizeIterator for FormattedIter +impl ExactSizeIterator for FormattedIter where Iter: Iterator + ExactSizeIterator, - Item: IntoFormat, + Item: IntoFormat, { } @@ -175,15 +181,15 @@ where { type Context = JsFormatContext; - fn format(node: &N, formatter: &Formatter) -> FormatResult { + fn fmt(node: &N, f: &mut JsFormatter) -> FormatResult<()> { let syntax = node.syntax(); - let element = if has_formatter_suppressions(syntax) { - suppressed_node(syntax).format(formatter)? + if has_formatter_suppressions(syntax) { + write!(f, [format_suppressed_node(syntax)])?; } else { - Self::format_fields(node, formatter)? + Self::fmt_fields(node, f)?; }; - Ok(element) + Ok(()) } } @@ -192,10 +198,7 @@ where T: AstNode, { /// Formats the node's fields. - fn format_fields( - item: &T, - formatter: &Formatter, - ) -> FormatResult; + fn fmt_fields(item: &T, f: &mut JsFormatter) -> FormatResult<()>; } /// Format implementation specific to JavaScript tokens. @@ -204,17 +207,17 @@ pub struct FormatJsSyntaxToken; impl FormatRule for FormatJsSyntaxToken { type Context = JsFormatContext; - fn format( - token: &JsSyntaxToken, - formatter: &Formatter, - ) -> FormatResult { - formatter.track_token(token); - - Ok(format_elements![ - format_leading_trivia(token, formatter::TriviaPrintMode::Full), - Token::from(token), - format_trailing_trivia(token), - ]) + fn fmt(token: &JsSyntaxToken, f: &mut JsFormatter) -> FormatResult<()> { + f.state_mut().track_token(token); + + write!( + f, + [ + format_leading_trivia(token, TriviaPrintMode::Full), + format_trimmed_token(token), + format_trailing_trivia(token), + ] + ) } } @@ -226,7 +229,7 @@ impl<'a> AsFormat<'a> for JsSyntaxToken { } } -impl IntoFormat for JsSyntaxToken { +impl IntoFormat for JsSyntaxToken { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format { @@ -237,7 +240,7 @@ impl IntoFormat for JsSyntaxToken { /// Formats a range within a file, supported by Rome /// /// This runs a simple heuristic to determine the initial indentation -/// level of the node based on the provided [FormatOptions], which +/// level of the node based on the provided [FormatContext], which /// must match currently the current initial of the file. Additionally, /// because the reformatting happens only locally the resulting code /// will be indented with the same level as the original selection, @@ -284,7 +287,7 @@ pub fn format_node(context: JsFormatContext, root: &JsSyntaxNode) -> FormatResul /// Formats a single node within a file, supported by Rome. /// /// This runs a simple heuristic to determine the initial indentation -/// level of the node based on the provided [FormatOptions], which +/// level of the node based on the provided [FormatContext], which /// must match currently the current initial of the file. Additionally, /// because the reformatting happens only locally the resulting code /// will be indented with the same level as the original selection, @@ -471,7 +474,9 @@ function() { mod check_reformat; #[rustfmt::skip] mod generated; +pub(crate) mod builders; pub mod context; +pub(crate) mod separated; #[cfg(test)] mod test { @@ -480,11 +485,11 @@ mod test { use rome_js_parser::parse; use rome_js_syntax::SourceType; - #[test] #[ignore] + #[test] // use this test check if your snippet prints as you wish, without using a snapshot fn quick_test() { - let src = r#"one.two.tree"#; + let src = r#"if (true) {}"#; let syntax = SourceType::tsx(); let tree = parse(src, 0, syntax); let result = format_node(JsFormatContext::default(), &tree.syntax()) diff --git a/crates/rome_js_formatter/src/prelude.rs b/crates/rome_js_formatter/src/prelude.rs index ed0b50cc10d..5ab954436d8 100644 --- a/crates/rome_js_formatter/src/prelude.rs +++ b/crates/rome_js_formatter/src/prelude.rs @@ -3,7 +3,16 @@ pub(crate) use crate::{ AsFormat as _, FormatNodeRule, FormattedIterExt, JsFormatContext, JsFormatter, - JsFormatterExt as _, }; pub use rome_formatter::prelude::*; pub use rome_rowan::{AstNode as _, AstNodeList as _, AstSeparatedList as _}; + +pub use crate::builders::{ + format_delimited, format_leading_trivia, format_or_verbatim, format_replaced, + format_suppressed_node, format_trailing_trivia, format_trimmed_token, format_unknown_node, + format_verbatim_node, +}; + +pub use crate::separated::{ + FormatAstSeparatedListExtension, FormatSeparatedOptions, TrailingSeparator, +}; diff --git a/crates/rome_js_formatter/src/separated.rs b/crates/rome_js_formatter/src/separated.rs new file mode 100644 index 00000000000..9c055b56119 --- /dev/null +++ b/crates/rome_js_formatter/src/separated.rs @@ -0,0 +1,201 @@ +use crate::prelude::*; +use crate::AsFormat; +use rome_formatter::{write, GroupId}; +use rome_js_syntax::JsLanguage; +use rome_rowan::{ + AstNode, AstSeparatedElement, AstSeparatedList, AstSeparatedListElementsIterator, Language, +}; +use std::iter::FusedIterator; + +/// Formats a single element inside of a separated list. +#[derive(Debug, Clone, Eq, PartialEq)] +pub struct FormatSeparatedElement { + element: AstSeparatedElement, + is_last: bool, + /// The separator to write if the element has no separator yet. + separator: Separator, + options: FormatSeparatedOptions, +} + +impl Format for FormatSeparatedElement +where + for<'a> N: AstNode + AsFormat<'a>, + Separator: Format, +{ + fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { + let node = self.element.node()?; + let separator = self.element.trailing_separator()?; + + write!(f, [group_elements(&node.format())])?; + + let format_trailing_separator = + if_group_breaks(&self.separator).with_group_id(self.options.group_id); + + // Reuse the existing trailing separator or create it if it wasn't in the + // input source. Only print the last trailing token if the outer group breaks + if let Some(separator) = separator { + if self.is_last { + match self.options.trailing_separator { + TrailingSeparator::Allowed => { + // Use format_replaced instead of wrapping the result of format_token + // in order to remove only the token itself when the group doesn't break + // but still print its associated trivias unconditionally + write!(f, [format_replaced(separator, &format_trailing_separator)])?; + } + TrailingSeparator::Mandatory => { + write!(f, [separator.format()])?; + } + TrailingSeparator::Disallowed => { + // A trailing separator was present where it wasn't allowed, opt out of formatting + return Err(FormatError::MissingRequiredChild); + } + } + } else { + write!(f, [separator.format()])?; + } + } else if self.is_last { + match self.options.trailing_separator { + TrailingSeparator::Allowed => { + write!(f, [format_trailing_separator])?; + } + TrailingSeparator::Mandatory => { + write!(f, [&self.separator])?; + } + TrailingSeparator::Disallowed => { /* no op */ } + } + } else { + write!(f, [&self.separator])?; + }; + + Ok(()) + } +} + +/// Iterator for formatting separated elements. Prints the separator between each element and +/// inserts a trailing separator if necessary +pub struct FormatSeparatedIter +where + Language: rome_rowan::Language, +{ + next: Option>, + inner: I, + separator: Separator, + options: FormatSeparatedOptions, +} + +impl FormatSeparatedIter +where + L: Language, +{ + fn new(inner: I, separator: Separator) -> Self { + Self { + inner, + separator, + next: None, + options: FormatSeparatedOptions::default(), + } + } + + pub fn with_options(mut self, options: FormatSeparatedOptions) -> Self { + self.options = options; + self + } +} + +impl Iterator for FormatSeparatedIter +where + I: Iterator>, + Separator: Copy, +{ + type Item = FormatSeparatedElement; + + fn next(&mut self) -> Option { + let element = self.next.take().or_else(|| self.inner.next())?; + + self.next = self.inner.next(); + let is_last = self.next.is_none(); + + Some(FormatSeparatedElement { + element, + is_last, + separator: self.separator, + options: self.options, + }) + } +} + +impl FusedIterator for FormatSeparatedIter +where + I: Iterator> + FusedIterator, + Separator: Copy, +{ +} + +impl ExactSizeIterator for FormatSeparatedIter +where + I: Iterator> + ExactSizeIterator, + Separator: Copy, +{ +} + +/// AST Separated list formatting extension methods +pub trait FormatAstSeparatedListExtension: AstSeparatedList { + /// Prints a separated list of nodes + /// + /// Trailing separators will be reused from the original list or + /// created by calling the `separator_factory` function. + /// The last trailing separator in the list will only be printed + /// if the outer group breaks. + fn format_separated( + &self, + separator: Separator, + ) -> FormatSeparatedIter< + AstSeparatedListElementsIterator, + JsLanguage, + Self::Node, + Separator, + > + where + Separator: Format + Copy, + { + FormatSeparatedIter::new(self.elements(), separator) + } +} + +impl FormatAstSeparatedListExtension for T where T: AstSeparatedList {} + +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub enum TrailingSeparator { + /// A trailing separator is allowed and preferred + Allowed, + + /// A trailing separator is not allowed + Disallowed, + + /// A trailing separator is mandatory for the syntax to be correct + Mandatory, +} + +impl Default for TrailingSeparator { + fn default() -> Self { + TrailingSeparator::Allowed + } +} + +#[derive(Debug, Default, Copy, Clone, Eq, PartialEq)] +pub struct FormatSeparatedOptions { + trailing_separator: TrailingSeparator, + group_id: Option, +} + +impl FormatSeparatedOptions { + pub fn with_trailing_separator(mut self, separator: TrailingSeparator) -> Self { + self.trailing_separator = separator; + self + } + + pub fn with_group_id(mut self, group_id: Option) -> Self { + self.group_id = group_id; + self + } +} diff --git a/crates/rome_js_formatter/src/ts/any/external_module_declaration_body.rs b/crates/rome_js_formatter/src/ts/any/external_module_declaration_body.rs index 5f4ebc1f905..580dc95476e 100644 --- a/crates/rome_js_formatter/src/ts/any/external_module_declaration_body.rs +++ b/crates/rome_js_formatter/src/ts/any/external_module_declaration_body.rs @@ -5,17 +5,12 @@ use crate::prelude::*; use rome_js_syntax::TsAnyExternalModuleDeclarationBody; impl FormatRule for FormatTsAnyExternalModuleDeclarationBody { type Context = JsFormatContext; - fn format( - node: &TsAnyExternalModuleDeclarationBody, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt(node: &TsAnyExternalModuleDeclarationBody, f: &mut JsFormatter) -> FormatResult<()> { match node { TsAnyExternalModuleDeclarationBody::TsEmptyExternalModuleDeclarationBody(node) => { - formatted![formatter, [node.format()]] - } - TsAnyExternalModuleDeclarationBody::TsModuleBlock(node) => { - formatted![formatter, [node.format()]] + node.format().fmt(f) } + TsAnyExternalModuleDeclarationBody::TsModuleBlock(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/ts/any/index_signature_modifier.rs b/crates/rome_js_formatter/src/ts/any/index_signature_modifier.rs index b4b52e4c483..c6326aba7a4 100644 --- a/crates/rome_js_formatter/src/ts/any/index_signature_modifier.rs +++ b/crates/rome_js_formatter/src/ts/any/index_signature_modifier.rs @@ -5,17 +5,10 @@ use crate::prelude::*; use rome_js_syntax::TsAnyIndexSignatureModifier; impl FormatRule for FormatTsAnyIndexSignatureModifier { type Context = JsFormatContext; - fn format( - node: &TsAnyIndexSignatureModifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt(node: &TsAnyIndexSignatureModifier, f: &mut JsFormatter) -> FormatResult<()> { match node { - TsAnyIndexSignatureModifier::JsStaticModifier(node) => { - formatted![formatter, [node.format()]] - } - TsAnyIndexSignatureModifier::TsReadonlyModifier(node) => { - formatted![formatter, [node.format()]] - } + TsAnyIndexSignatureModifier::JsStaticModifier(node) => node.format().fmt(f), + TsAnyIndexSignatureModifier::TsReadonlyModifier(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/ts/any/method_signature_modifier.rs b/crates/rome_js_formatter/src/ts/any/method_signature_modifier.rs index d9103fe463d..142ccf07eaf 100644 --- a/crates/rome_js_formatter/src/ts/any/method_signature_modifier.rs +++ b/crates/rome_js_formatter/src/ts/any/method_signature_modifier.rs @@ -5,23 +5,12 @@ use crate::prelude::*; use rome_js_syntax::TsAnyMethodSignatureModifier; impl FormatRule for FormatTsAnyMethodSignatureModifier { type Context = JsFormatContext; - fn format( - node: &TsAnyMethodSignatureModifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt(node: &TsAnyMethodSignatureModifier, f: &mut JsFormatter) -> FormatResult<()> { match node { - TsAnyMethodSignatureModifier::TsAccessibilityModifier(node) => { - formatted![formatter, [node.format()]] - } - TsAnyMethodSignatureModifier::JsStaticModifier(node) => { - formatted![formatter, [node.format()]] - } - TsAnyMethodSignatureModifier::TsOverrideModifier(node) => { - formatted![formatter, [node.format()]] - } - TsAnyMethodSignatureModifier::TsAbstractModifier(node) => { - formatted![formatter, [node.format()]] - } + TsAnyMethodSignatureModifier::TsAccessibilityModifier(node) => node.format().fmt(f), + TsAnyMethodSignatureModifier::JsStaticModifier(node) => node.format().fmt(f), + TsAnyMethodSignatureModifier::TsOverrideModifier(node) => node.format().fmt(f), + TsAnyMethodSignatureModifier::TsAbstractModifier(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/ts/any/module_name.rs b/crates/rome_js_formatter/src/ts/any/module_name.rs index ecc2745c11d..160c8a38464 100644 --- a/crates/rome_js_formatter/src/ts/any/module_name.rs +++ b/crates/rome_js_formatter/src/ts/any/module_name.rs @@ -5,10 +5,10 @@ use crate::prelude::*; use rome_js_syntax::TsAnyModuleName; impl FormatRule for FormatTsAnyModuleName { type Context = JsFormatContext; - fn format(node: &TsAnyModuleName, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &TsAnyModuleName, f: &mut JsFormatter) -> FormatResult<()> { match node { - TsAnyModuleName::TsIdentifierBinding(node) => formatted![formatter, [node.format()]], - TsAnyModuleName::TsQualifiedModuleName(node) => formatted![formatter, [node.format()]], + TsAnyModuleName::TsIdentifierBinding(node) => node.format().fmt(f), + TsAnyModuleName::TsQualifiedModuleName(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/ts/any/module_reference.rs b/crates/rome_js_formatter/src/ts/any/module_reference.rs index af4b13e4d4a..cd5841c06bf 100644 --- a/crates/rome_js_formatter/src/ts/any/module_reference.rs +++ b/crates/rome_js_formatter/src/ts/any/module_reference.rs @@ -5,12 +5,10 @@ use crate::prelude::*; use rome_js_syntax::TsAnyModuleReference; impl FormatRule for FormatTsAnyModuleReference { type Context = JsFormatContext; - fn format(node: &TsAnyModuleReference, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &TsAnyModuleReference, f: &mut JsFormatter) -> FormatResult<()> { match node { - TsAnyModuleReference::TsAnyName(node) => formatted![formatter, [node.format()]], - TsAnyModuleReference::TsExternalModuleReference(node) => { - formatted![formatter, [node.format()]] - } + TsAnyModuleReference::TsAnyName(node) => node.format().fmt(f), + TsAnyModuleReference::TsExternalModuleReference(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/ts/any/name.rs b/crates/rome_js_formatter/src/ts/any/name.rs index 2df5789aa21..0bf9a1f2018 100644 --- a/crates/rome_js_formatter/src/ts/any/name.rs +++ b/crates/rome_js_formatter/src/ts/any/name.rs @@ -5,10 +5,10 @@ use crate::prelude::*; use rome_js_syntax::TsAnyName; impl FormatRule for FormatTsAnyName { type Context = JsFormatContext; - fn format(node: &TsAnyName, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &TsAnyName, f: &mut JsFormatter) -> FormatResult<()> { match node { - TsAnyName::JsReferenceIdentifier(node) => formatted![formatter, [node.format()]], - TsAnyName::TsQualifiedName(node) => formatted![formatter, [node.format()]], + TsAnyName::JsReferenceIdentifier(node) => node.format().fmt(f), + TsAnyName::TsQualifiedName(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/ts/any/property_annotation.rs b/crates/rome_js_formatter/src/ts/any/property_annotation.rs index 79de7466082..6c9da1e7af9 100644 --- a/crates/rome_js_formatter/src/ts/any/property_annotation.rs +++ b/crates/rome_js_formatter/src/ts/any/property_annotation.rs @@ -5,20 +5,11 @@ use crate::prelude::*; use rome_js_syntax::TsAnyPropertyAnnotation; impl FormatRule for FormatTsAnyPropertyAnnotation { type Context = JsFormatContext; - fn format( - node: &TsAnyPropertyAnnotation, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt(node: &TsAnyPropertyAnnotation, f: &mut JsFormatter) -> FormatResult<()> { match node { - TsAnyPropertyAnnotation::TsTypeAnnotation(node) => { - formatted![formatter, [node.format()]] - } - TsAnyPropertyAnnotation::TsOptionalPropertyAnnotation(node) => { - formatted![formatter, [node.format()]] - } - TsAnyPropertyAnnotation::TsDefinitePropertyAnnotation(node) => { - formatted![formatter, [node.format()]] - } + TsAnyPropertyAnnotation::TsTypeAnnotation(node) => node.format().fmt(f), + TsAnyPropertyAnnotation::TsOptionalPropertyAnnotation(node) => node.format().fmt(f), + TsAnyPropertyAnnotation::TsDefinitePropertyAnnotation(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/ts/any/property_parameter_modifier.rs b/crates/rome_js_formatter/src/ts/any/property_parameter_modifier.rs index d379ffabf58..b02a8ab2b99 100644 --- a/crates/rome_js_formatter/src/ts/any/property_parameter_modifier.rs +++ b/crates/rome_js_formatter/src/ts/any/property_parameter_modifier.rs @@ -5,20 +5,11 @@ use crate::prelude::*; use rome_js_syntax::TsAnyPropertyParameterModifier; impl FormatRule for FormatTsAnyPropertyParameterModifier { type Context = JsFormatContext; - fn format( - node: &TsAnyPropertyParameterModifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt(node: &TsAnyPropertyParameterModifier, f: &mut JsFormatter) -> FormatResult<()> { match node { - TsAnyPropertyParameterModifier::TsAccessibilityModifier(node) => { - formatted![formatter, [node.format()]] - } - TsAnyPropertyParameterModifier::TsReadonlyModifier(node) => { - formatted![formatter, [node.format()]] - } - TsAnyPropertyParameterModifier::TsOverrideModifier(node) => { - formatted![formatter, [node.format()]] - } + TsAnyPropertyParameterModifier::TsAccessibilityModifier(node) => node.format().fmt(f), + TsAnyPropertyParameterModifier::TsReadonlyModifier(node) => node.format().fmt(f), + TsAnyPropertyParameterModifier::TsOverrideModifier(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/ts/any/property_signature_annotation.rs b/crates/rome_js_formatter/src/ts/any/property_signature_annotation.rs index 981d6dcf677..aa6546fb5d1 100644 --- a/crates/rome_js_formatter/src/ts/any/property_signature_annotation.rs +++ b/crates/rome_js_formatter/src/ts/any/property_signature_annotation.rs @@ -5,16 +5,11 @@ use crate::prelude::*; use rome_js_syntax::TsAnyPropertySignatureAnnotation; impl FormatRule for FormatTsAnyPropertySignatureAnnotation { type Context = JsFormatContext; - fn format( - node: &TsAnyPropertySignatureAnnotation, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt(node: &TsAnyPropertySignatureAnnotation, f: &mut JsFormatter) -> FormatResult<()> { match node { - TsAnyPropertySignatureAnnotation::TsTypeAnnotation(node) => { - formatted![formatter, [node.format()]] - } + TsAnyPropertySignatureAnnotation::TsTypeAnnotation(node) => node.format().fmt(f), TsAnyPropertySignatureAnnotation::TsOptionalPropertyAnnotation(node) => { - formatted![formatter, [node.format()]] + node.format().fmt(f) } } } diff --git a/crates/rome_js_formatter/src/ts/any/property_signature_modifier.rs b/crates/rome_js_formatter/src/ts/any/property_signature_modifier.rs index aa70743e6d0..37274ec85de 100644 --- a/crates/rome_js_formatter/src/ts/any/property_signature_modifier.rs +++ b/crates/rome_js_formatter/src/ts/any/property_signature_modifier.rs @@ -5,29 +5,14 @@ use crate::prelude::*; use rome_js_syntax::TsAnyPropertySignatureModifier; impl FormatRule for FormatTsAnyPropertySignatureModifier { type Context = JsFormatContext; - fn format( - node: &TsAnyPropertySignatureModifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt(node: &TsAnyPropertySignatureModifier, f: &mut JsFormatter) -> FormatResult<()> { match node { - TsAnyPropertySignatureModifier::TsDeclareModifier(node) => { - formatted![formatter, [node.format()]] - } - TsAnyPropertySignatureModifier::TsAccessibilityModifier(node) => { - formatted![formatter, [node.format()]] - } - TsAnyPropertySignatureModifier::JsStaticModifier(node) => { - formatted![formatter, [node.format()]] - } - TsAnyPropertySignatureModifier::TsReadonlyModifier(node) => { - formatted![formatter, [node.format()]] - } - TsAnyPropertySignatureModifier::TsOverrideModifier(node) => { - formatted![formatter, [node.format()]] - } - TsAnyPropertySignatureModifier::TsAbstractModifier(node) => { - formatted![formatter, [node.format()]] - } + TsAnyPropertySignatureModifier::TsDeclareModifier(node) => node.format().fmt(f), + TsAnyPropertySignatureModifier::TsAccessibilityModifier(node) => node.format().fmt(f), + TsAnyPropertySignatureModifier::JsStaticModifier(node) => node.format().fmt(f), + TsAnyPropertySignatureModifier::TsReadonlyModifier(node) => node.format().fmt(f), + TsAnyPropertySignatureModifier::TsOverrideModifier(node) => node.format().fmt(f), + TsAnyPropertySignatureModifier::TsAbstractModifier(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/ts/any/return_type.rs b/crates/rome_js_formatter/src/ts/any/return_type.rs index 013338d613a..04c3c7b8f99 100644 --- a/crates/rome_js_formatter/src/ts/any/return_type.rs +++ b/crates/rome_js_formatter/src/ts/any/return_type.rs @@ -5,11 +5,11 @@ use crate::prelude::*; use rome_js_syntax::TsAnyReturnType; impl FormatRule for FormatTsAnyReturnType { type Context = JsFormatContext; - fn format(node: &TsAnyReturnType, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &TsAnyReturnType, f: &mut JsFormatter) -> FormatResult<()> { match node { - TsAnyReturnType::TsType(node) => formatted![formatter, [node.format()]], - TsAnyReturnType::TsPredicateReturnType(node) => formatted![formatter, [node.format()]], - TsAnyReturnType::TsAssertsReturnType(node) => formatted![formatter, [node.format()]], + TsAnyReturnType::TsType(node) => node.format().fmt(f), + TsAnyReturnType::TsPredicateReturnType(node) => node.format().fmt(f), + TsAnyReturnType::TsAssertsReturnType(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/ts/any/template_element.rs b/crates/rome_js_formatter/src/ts/any/template_element.rs index 14eae0e051e..3c5b4d07897 100644 --- a/crates/rome_js_formatter/src/ts/any/template_element.rs +++ b/crates/rome_js_formatter/src/ts/any/template_element.rs @@ -5,12 +5,10 @@ use crate::prelude::*; use rome_js_syntax::TsAnyTemplateElement; impl FormatRule for FormatTsAnyTemplateElement { type Context = JsFormatContext; - fn format(node: &TsAnyTemplateElement, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &TsAnyTemplateElement, f: &mut JsFormatter) -> FormatResult<()> { match node { - TsAnyTemplateElement::TsTemplateChunkElement(node) => { - formatted![formatter, [node.format()]] - } - TsAnyTemplateElement::TsTemplateElement(node) => formatted![formatter, [node.format()]], + TsAnyTemplateElement::TsTemplateChunkElement(node) => node.format().fmt(f), + TsAnyTemplateElement::TsTemplateElement(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/ts/any/ts_type.rs b/crates/rome_js_formatter/src/ts/any/ts_type.rs index ca52e8c866b..428e5f5c475 100644 --- a/crates/rome_js_formatter/src/ts/any/ts_type.rs +++ b/crates/rome_js_formatter/src/ts/any/ts_type.rs @@ -5,42 +5,42 @@ use crate::prelude::*; use rome_js_syntax::TsType; impl FormatRule for FormatTsType { type Context = JsFormatContext; - fn format(node: &TsType, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &TsType, f: &mut JsFormatter) -> FormatResult<()> { match node { - TsType::TsAnyType(node) => formatted![formatter, [node.format()]], - TsType::TsUnknownType(node) => formatted![formatter, [node.format()]], - TsType::TsNumberType(node) => formatted![formatter, [node.format()]], - TsType::TsBooleanType(node) => formatted![formatter, [node.format()]], - TsType::TsBigintType(node) => formatted![formatter, [node.format()]], - TsType::TsStringType(node) => formatted![formatter, [node.format()]], - TsType::TsSymbolType(node) => formatted![formatter, [node.format()]], - TsType::TsVoidType(node) => formatted![formatter, [node.format()]], - TsType::TsUndefinedType(node) => formatted![formatter, [node.format()]], - TsType::TsNeverType(node) => formatted![formatter, [node.format()]], - TsType::TsParenthesizedType(node) => formatted![formatter, [node.format()]], - TsType::TsReferenceType(node) => formatted![formatter, [node.format()]], - TsType::TsArrayType(node) => formatted![formatter, [node.format()]], - TsType::TsTupleType(node) => formatted![formatter, [node.format()]], - TsType::TsTypeofType(node) => formatted![formatter, [node.format()]], - TsType::TsImportType(node) => formatted![formatter, [node.format()]], - TsType::TsTypeOperatorType(node) => formatted![formatter, [node.format()]], - TsType::TsIndexedAccessType(node) => formatted![formatter, [node.format()]], - TsType::TsMappedType(node) => formatted![formatter, [node.format()]], - TsType::TsObjectType(node) => formatted![formatter, [node.format()]], - TsType::TsNonPrimitiveType(node) => formatted![formatter, [node.format()]], - TsType::TsThisType(node) => formatted![formatter, [node.format()]], - TsType::TsNumberLiteralType(node) => formatted![formatter, [node.format()]], - TsType::TsBigIntLiteralType(node) => formatted![formatter, [node.format()]], - TsType::TsStringLiteralType(node) => formatted![formatter, [node.format()]], - TsType::TsNullLiteralType(node) => formatted![formatter, [node.format()]], - TsType::TsBooleanLiteralType(node) => formatted![formatter, [node.format()]], - TsType::TsTemplateLiteralType(node) => formatted![formatter, [node.format()]], - TsType::TsInferType(node) => formatted![formatter, [node.format()]], - TsType::TsIntersectionType(node) => formatted![formatter, [node.format()]], - TsType::TsUnionType(node) => formatted![formatter, [node.format()]], - TsType::TsFunctionType(node) => formatted![formatter, [node.format()]], - TsType::TsConstructorType(node) => formatted![formatter, [node.format()]], - TsType::TsConditionalType(node) => formatted![formatter, [node.format()]], + TsType::TsAnyType(node) => node.format().fmt(f), + TsType::TsUnknownType(node) => node.format().fmt(f), + TsType::TsNumberType(node) => node.format().fmt(f), + TsType::TsBooleanType(node) => node.format().fmt(f), + TsType::TsBigintType(node) => node.format().fmt(f), + TsType::TsStringType(node) => node.format().fmt(f), + TsType::TsSymbolType(node) => node.format().fmt(f), + TsType::TsVoidType(node) => node.format().fmt(f), + TsType::TsUndefinedType(node) => node.format().fmt(f), + TsType::TsNeverType(node) => node.format().fmt(f), + TsType::TsParenthesizedType(node) => node.format().fmt(f), + TsType::TsReferenceType(node) => node.format().fmt(f), + TsType::TsArrayType(node) => node.format().fmt(f), + TsType::TsTupleType(node) => node.format().fmt(f), + TsType::TsTypeofType(node) => node.format().fmt(f), + TsType::TsImportType(node) => node.format().fmt(f), + TsType::TsTypeOperatorType(node) => node.format().fmt(f), + TsType::TsIndexedAccessType(node) => node.format().fmt(f), + TsType::TsMappedType(node) => node.format().fmt(f), + TsType::TsObjectType(node) => node.format().fmt(f), + TsType::TsNonPrimitiveType(node) => node.format().fmt(f), + TsType::TsThisType(node) => node.format().fmt(f), + TsType::TsNumberLiteralType(node) => node.format().fmt(f), + TsType::TsBigIntLiteralType(node) => node.format().fmt(f), + TsType::TsStringLiteralType(node) => node.format().fmt(f), + TsType::TsNullLiteralType(node) => node.format().fmt(f), + TsType::TsBooleanLiteralType(node) => node.format().fmt(f), + TsType::TsTemplateLiteralType(node) => node.format().fmt(f), + TsType::TsInferType(node) => node.format().fmt(f), + TsType::TsIntersectionType(node) => node.format().fmt(f), + TsType::TsUnionType(node) => node.format().fmt(f), + TsType::TsFunctionType(node) => node.format().fmt(f), + TsType::TsConstructorType(node) => node.format().fmt(f), + TsType::TsConditionalType(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/ts/any/tuple_type_element.rs b/crates/rome_js_formatter/src/ts/any/tuple_type_element.rs index c7107bd20c1..ac53f19609f 100644 --- a/crates/rome_js_formatter/src/ts/any/tuple_type_element.rs +++ b/crates/rome_js_formatter/src/ts/any/tuple_type_element.rs @@ -5,21 +5,12 @@ use crate::prelude::*; use rome_js_syntax::TsAnyTupleTypeElement; impl FormatRule for FormatTsAnyTupleTypeElement { type Context = JsFormatContext; - fn format( - node: &TsAnyTupleTypeElement, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt(node: &TsAnyTupleTypeElement, f: &mut JsFormatter) -> FormatResult<()> { match node { - TsAnyTupleTypeElement::TsNamedTupleTypeElement(node) => { - formatted![formatter, [node.format()]] - } - TsAnyTupleTypeElement::TsType(node) => formatted![formatter, [node.format()]], - TsAnyTupleTypeElement::TsRestTupleTypeElement(node) => { - formatted![formatter, [node.format()]] - } - TsAnyTupleTypeElement::TsOptionalTupleTypeElement(node) => { - formatted![formatter, [node.format()]] - } + TsAnyTupleTypeElement::TsNamedTupleTypeElement(node) => node.format().fmt(f), + TsAnyTupleTypeElement::TsType(node) => node.format().fmt(f), + TsAnyTupleTypeElement::TsRestTupleTypeElement(node) => node.format().fmt(f), + TsAnyTupleTypeElement::TsOptionalTupleTypeElement(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/ts/any/type_member.rs b/crates/rome_js_formatter/src/ts/any/type_member.rs index 1561dc87c58..54a47a4f4e4 100644 --- a/crates/rome_js_formatter/src/ts/any/type_member.rs +++ b/crates/rome_js_formatter/src/ts/any/type_member.rs @@ -5,30 +5,16 @@ use crate::prelude::*; use rome_js_syntax::TsAnyTypeMember; impl FormatRule for FormatTsAnyTypeMember { type Context = JsFormatContext; - fn format(node: &TsAnyTypeMember, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &TsAnyTypeMember, f: &mut JsFormatter) -> FormatResult<()> { match node { - TsAnyTypeMember::TsCallSignatureTypeMember(node) => { - formatted![formatter, [node.format()]] - } - TsAnyTypeMember::TsPropertySignatureTypeMember(node) => { - formatted![formatter, [node.format()]] - } - TsAnyTypeMember::TsConstructSignatureTypeMember(node) => { - formatted![formatter, [node.format()]] - } - TsAnyTypeMember::TsMethodSignatureTypeMember(node) => { - formatted![formatter, [node.format()]] - } - TsAnyTypeMember::TsGetterSignatureTypeMember(node) => { - formatted![formatter, [node.format()]] - } - TsAnyTypeMember::TsSetterSignatureTypeMember(node) => { - formatted![formatter, [node.format()]] - } - TsAnyTypeMember::TsIndexSignatureTypeMember(node) => { - formatted![formatter, [node.format()]] - } - TsAnyTypeMember::JsUnknownMember(node) => formatted![formatter, [node.format()]], + TsAnyTypeMember::TsCallSignatureTypeMember(node) => node.format().fmt(f), + TsAnyTypeMember::TsPropertySignatureTypeMember(node) => node.format().fmt(f), + TsAnyTypeMember::TsConstructSignatureTypeMember(node) => node.format().fmt(f), + TsAnyTypeMember::TsMethodSignatureTypeMember(node) => node.format().fmt(f), + TsAnyTypeMember::TsGetterSignatureTypeMember(node) => node.format().fmt(f), + TsAnyTypeMember::TsSetterSignatureTypeMember(node) => node.format().fmt(f), + TsAnyTypeMember::TsIndexSignatureTypeMember(node) => node.format().fmt(f), + TsAnyTypeMember::JsUnknownMember(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/ts/any/type_predicate_parameter_name.rs b/crates/rome_js_formatter/src/ts/any/type_predicate_parameter_name.rs index 0b7dc083233..9be89c54c4d 100644 --- a/crates/rome_js_formatter/src/ts/any/type_predicate_parameter_name.rs +++ b/crates/rome_js_formatter/src/ts/any/type_predicate_parameter_name.rs @@ -5,17 +5,10 @@ use crate::prelude::*; use rome_js_syntax::TsAnyTypePredicateParameterName; impl FormatRule for FormatTsAnyTypePredicateParameterName { type Context = JsFormatContext; - fn format( - node: &TsAnyTypePredicateParameterName, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt(node: &TsAnyTypePredicateParameterName, f: &mut JsFormatter) -> FormatResult<()> { match node { - TsAnyTypePredicateParameterName::JsReferenceIdentifier(node) => { - formatted![formatter, [node.format()]] - } - TsAnyTypePredicateParameterName::TsThisType(node) => { - formatted![formatter, [node.format()]] - } + TsAnyTypePredicateParameterName::JsReferenceIdentifier(node) => node.format().fmt(f), + TsAnyTypePredicateParameterName::TsThisType(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/ts/any/variable_annotation.rs b/crates/rome_js_formatter/src/ts/any/variable_annotation.rs index a5224b5df19..3c5134b34d4 100644 --- a/crates/rome_js_formatter/src/ts/any/variable_annotation.rs +++ b/crates/rome_js_formatter/src/ts/any/variable_annotation.rs @@ -5,17 +5,10 @@ use crate::prelude::*; use rome_js_syntax::TsAnyVariableAnnotation; impl FormatRule for FormatTsAnyVariableAnnotation { type Context = JsFormatContext; - fn format( - node: &TsAnyVariableAnnotation, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt(node: &TsAnyVariableAnnotation, f: &mut JsFormatter) -> FormatResult<()> { match node { - TsAnyVariableAnnotation::TsTypeAnnotation(node) => { - formatted![formatter, [node.format()]] - } - TsAnyVariableAnnotation::TsDefiniteVariableAnnotation(node) => { - formatted![formatter, [node.format()]] - } + TsAnyVariableAnnotation::TsTypeAnnotation(node) => node.format().fmt(f), + TsAnyVariableAnnotation::TsDefiniteVariableAnnotation(node) => node.format().fmt(f), } } } diff --git a/crates/rome_js_formatter/src/ts/assignments/as_assignment.rs b/crates/rome_js_formatter/src/ts/assignments/as_assignment.rs index 46bf8055b77..27bea467c56 100644 --- a/crates/rome_js_formatter/src/ts/assignments/as_assignment.rs +++ b/crates/rome_js_formatter/src/ts/assignments/as_assignment.rs @@ -1,21 +1,19 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsAsAssignment; use rome_js_syntax::TsAsAssignmentFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsAsAssignment, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsAsAssignment, f: &mut JsFormatter) -> FormatResult<()> { let TsAsAssignmentFields { assignment, as_token, ty, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ assignment.format(), space_token(), diff --git a/crates/rome_js_formatter/src/ts/assignments/non_null_assertion_assignment.rs b/crates/rome_js_formatter/src/ts/assignments/non_null_assertion_assignment.rs index 2ee989e9d42..7b8be795d34 100644 --- a/crates/rome_js_formatter/src/ts/assignments/non_null_assertion_assignment.rs +++ b/crates/rome_js_formatter/src/ts/assignments/non_null_assertion_assignment.rs @@ -1,19 +1,17 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsNonNullAssertionAssignment; use rome_js_syntax::TsNonNullAssertionAssignmentFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsNonNullAssertionAssignment, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsNonNullAssertionAssignment, f: &mut JsFormatter) -> FormatResult<()> { let TsNonNullAssertionAssignmentFields { assignment, excl_token, } = node.as_fields(); - formatted![formatter, [assignment.format(), excl_token.format()]] + write![f, [assignment.format(), excl_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/assignments/type_assertion_assignment.rs b/crates/rome_js_formatter/src/ts/assignments/type_assertion_assignment.rs index 13bd544fe63..9dfc3cb5029 100644 --- a/crates/rome_js_formatter/src/ts/assignments/type_assertion_assignment.rs +++ b/crates/rome_js_formatter/src/ts/assignments/type_assertion_assignment.rs @@ -1,14 +1,12 @@ use crate::prelude::*; +use rome_formatter::write; use rome_js_syntax::TsTypeAssertionAssignmentFields; use crate::FormatNodeFields; use rome_js_syntax::TsTypeAssertionAssignment; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsTypeAssertionAssignment, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsTypeAssertionAssignment, f: &mut JsFormatter) -> FormatResult<()> { let TsTypeAssertionAssignmentFields { l_angle_token, ty, @@ -16,17 +14,11 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &TsAbstractModifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsAbstractModifier, f: &mut JsFormatter) -> FormatResult<()> { let TsAbstractModifierFields { modifier_token } = node.as_fields(); - formatted![formatter, [modifier_token.format()]] + write![f, [modifier_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/accessibility_modifier.rs b/crates/rome_js_formatter/src/ts/auxiliary/accessibility_modifier.rs index 5f1d20b41ec..abebce0ff07 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/accessibility_modifier.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/accessibility_modifier.rs @@ -1,15 +1,13 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsAccessibilityModifier; use rome_js_syntax::TsAccessibilityModifierFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsAccessibilityModifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsAccessibilityModifier, f: &mut JsFormatter) -> FormatResult<()> { let TsAccessibilityModifierFields { modifier_token } = node.as_fields(); - formatted![formatter, [modifier_token.format()]] + write![f, [modifier_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/asserts_condition.rs b/crates/rome_js_formatter/src/ts/auxiliary/asserts_condition.rs index 9b454737336..5133d783fe0 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/asserts_condition.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/asserts_condition.rs @@ -1,14 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsAssertsCondition; use rome_js_syntax::TsAssertsConditionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsAssertsCondition, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsAssertsCondition, f: &mut JsFormatter) -> FormatResult<()> { let TsAssertsConditionFields { is_token, ty } = node.as_fields(); - formatted![formatter, [is_token.format(), space_token(), ty.format()]] + write![f, [is_token.format(), space_token(), ty.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/call_signature_type_member.rs b/crates/rome_js_formatter/src/ts/auxiliary/call_signature_type_member.rs index 2bf2e646392..b8420e8b9aa 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/call_signature_type_member.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/call_signature_type_member.rs @@ -1,13 +1,11 @@ use crate::prelude::*; -use crate::utils::format_type_member_separator; +use crate::utils::FormatTypeMemberSeparator; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsCallSignatureTypeMember, TsCallSignatureTypeMemberFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsCallSignatureTypeMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsCallSignatureTypeMember, f: &mut JsFormatter) -> FormatResult<()> { let TsCallSignatureTypeMemberFields { type_parameters, parameters, @@ -15,16 +13,14 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &TsConstructSignatureTypeMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsConstructSignatureTypeMember, f: &mut JsFormatter) -> FormatResult<()> { let TsConstructSignatureTypeMemberFields { new_token, type_parameters, @@ -18,17 +17,15 @@ impl FormatNodeFields separator_token, } = node.as_fields(); - let separator_token = format_type_member_separator(separator_token, formatter); - - formatted![ - formatter, + write![ + f, [ new_token.format(), space_token(), type_parameters.format(), parameters.format(), type_annotation.format(), - separator_token, + FormatTypeMemberSeparator::new(separator_token.as_ref()), ] ] } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/declare_modifier.rs b/crates/rome_js_formatter/src/ts/auxiliary/declare_modifier.rs index 3069febc6f9..bd900010471 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/declare_modifier.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/declare_modifier.rs @@ -1,14 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsDeclareModifier; use rome_js_syntax::TsDeclareModifierFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsDeclareModifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsDeclareModifier, f: &mut JsFormatter) -> FormatResult<()> { let TsDeclareModifierFields { modifier_token } = node.as_fields(); - formatted![formatter, [modifier_token.format()]] + write![f, [modifier_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/default_type_clause.rs b/crates/rome_js_formatter/src/ts/auxiliary/default_type_clause.rs index 77364d4315c..fdbc7913be4 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/default_type_clause.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/default_type_clause.rs @@ -1,13 +1,11 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsDefaultTypeClause, TsDefaultTypeClauseFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsDefaultTypeClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsDefaultTypeClause, f: &mut JsFormatter) -> FormatResult<()> { let TsDefaultTypeClauseFields { eq_token, ty } = node.as_fields(); - formatted![formatter, [eq_token.format(), space_token(), ty.format()]] + write![f, [eq_token.format(), space_token(), ty.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/definite_property_annotation.rs b/crates/rome_js_formatter/src/ts/auxiliary/definite_property_annotation.rs index 794bf55fe0c..67b81e363fe 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/definite_property_annotation.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/definite_property_annotation.rs @@ -1,19 +1,18 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsDefinitePropertyAnnotation; use rome_js_syntax::TsDefinitePropertyAnnotationFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsDefinitePropertyAnnotation, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsDefinitePropertyAnnotation, f: &mut JsFormatter) -> FormatResult<()> { let TsDefinitePropertyAnnotationFields { excl_token, type_annotation, } = node.as_fields(); - formatted![formatter, [excl_token.format(), type_annotation.format()]] + + write![f, [excl_token.format(), type_annotation.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/definite_variable_annotation.rs b/crates/rome_js_formatter/src/ts/auxiliary/definite_variable_annotation.rs index 03bc7adc7a0..974ddc0eaf1 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/definite_variable_annotation.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/definite_variable_annotation.rs @@ -1,20 +1,18 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsDefiniteVariableAnnotation; use rome_js_syntax::TsDefiniteVariableAnnotationFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsDefiniteVariableAnnotation, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsDefiniteVariableAnnotation, f: &mut JsFormatter) -> FormatResult<()> { let TsDefiniteVariableAnnotationFields { excl_token, type_annotation, } = node.as_fields(); - formatted![formatter, [excl_token.format(), type_annotation.format(),]] + write![f, [excl_token.format(), type_annotation.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/empty_external_module_declaration_body.rs b/crates/rome_js_formatter/src/ts/auxiliary/empty_external_module_declaration_body.rs index a13a86a9d7f..3d7d349689e 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/empty_external_module_declaration_body.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/empty_external_module_declaration_body.rs @@ -1,16 +1,17 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsEmptyExternalModuleDeclarationBody; use rome_js_syntax::TsEmptyExternalModuleDeclarationBodyFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( + fn fmt_fields( node: &TsEmptyExternalModuleDeclarationBody, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut JsFormatter, + ) -> FormatResult<()> { let TsEmptyExternalModuleDeclarationBodyFields { semicolon_token } = node.as_fields(); - formatted![formatter, [semicolon_token.format()]] + write![f, [semicolon_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/enum_member.rs b/crates/rome_js_formatter/src/ts/auxiliary/enum_member.rs index 356e00e0661..5d30079c096 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/enum_member.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/enum_member.rs @@ -1,15 +1,19 @@ use crate::prelude::*; -use crate::utils::format_initializer_clause; +use crate::utils::FormatInitializerClause; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsEnumMember, TsEnumMemberFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsEnumMember, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &TsEnumMember, f: &mut JsFormatter) -> FormatResult<()> { let TsEnumMemberFields { name, initializer } = node.as_fields(); - let name = name.format(); - let initializer = format_initializer_clause(formatter, initializer)?; - - formatted![formatter, [name, initializer]] + write!( + f, + [ + name.format(), + FormatInitializerClause::new(initializer.as_ref()) + ] + ) } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/external_module_reference.rs b/crates/rome_js_formatter/src/ts/auxiliary/external_module_reference.rs index 131525d8ea4..8d8343727a2 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/external_module_reference.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/external_module_reference.rs @@ -1,13 +1,11 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsExternalModuleReference; use rome_js_syntax::TsExternalModuleReferenceFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsExternalModuleReference, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsExternalModuleReference, f: &mut JsFormatter) -> FormatResult<()> { let TsExternalModuleReferenceFields { require_token, l_paren_token, @@ -15,8 +13,8 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &TsGetterSignatureTypeMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsGetterSignatureTypeMember, f: &mut JsFormatter) -> FormatResult<()> { let TsGetterSignatureTypeMemberFields { get_token, name, @@ -17,10 +15,8 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &TsImplementsClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsImplementsClause, f: &mut JsFormatter) -> FormatResult<()> { let TsImplementsClauseFields { implements_token, types, @@ -16,22 +14,16 @@ impl FormatNodeFields for FormatNodeRule let implements_token = implements_token.format().memoized(); let types = types.format().memoized(); - Ok(group_elements(formatted![ - formatter, - [ - if_group_breaks(block_indent(formatted![ - formatter, - [ - &implements_token, - space_token(), - soft_block_indent(formatted![formatter, [&types]]?) - ] - ]?)), - if_group_fits_on_single_line(formatted![ - formatter, - [&implements_token, space_token(), &types] - ]?), - ] - ]?)) + write!( + f, + [group_elements(&format_args![ + if_group_breaks(&block_indent(&format_args![ + &implements_token, + space_token(), + soft_block_indent(&types) + ])), + if_group_fits_on_line(&format_args![&implements_token, space_token(), &types]), + ])] + ) } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/index_signature_type_member.rs b/crates/rome_js_formatter/src/ts/auxiliary/index_signature_type_member.rs index 6056883e55b..1d9eb69b599 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/index_signature_type_member.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/index_signature_type_member.rs @@ -1,13 +1,11 @@ use crate::prelude::*; -use crate::utils::format_type_member_separator; +use crate::utils::FormatTypeMemberSeparator; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsIndexSignatureTypeMember, TsIndexSignatureTypeMemberFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsIndexSignatureTypeMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsIndexSignatureTypeMember, f: &mut JsFormatter) -> FormatResult<()> { let TsIndexSignatureTypeMemberFields { readonly_token, l_brack_token, @@ -17,20 +15,18 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &TsMappedTypeAsClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsMappedTypeAsClause, f: &mut JsFormatter) -> FormatResult<()> { let TsMappedTypeAsClauseFields { as_token, ty } = node.as_fields(); - formatted![ - formatter, - [ - as_token - .format() - .with(|as_token| { formatted![formatter, [as_token, space_token()]] }), - ty.format() - ] - ] + write![f, [as_token.format(), space_token(), ty.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/mapped_type_optional_modifier_clause.rs b/crates/rome_js_formatter/src/ts/auxiliary/mapped_type_optional_modifier_clause.rs index 01adae8c431..90b1e85ea2e 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/mapped_type_optional_modifier_clause.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/mapped_type_optional_modifier_clause.rs @@ -1,23 +1,21 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsMappedTypeOptionalModifierClause; use rome_js_syntax::TsMappedTypeOptionalModifierClauseFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( + fn fmt_fields( node: &TsMappedTypeOptionalModifierClause, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut JsFormatter, + ) -> FormatResult<()> { let TsMappedTypeOptionalModifierClauseFields { operator_token, question_mark_token, } = node.as_fields(); - formatted![ - formatter, - [operator_token.format(), question_mark_token.format()] - ] + write![f, [operator_token.format(), question_mark_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/mapped_type_readonly_modifier_clause.rs b/crates/rome_js_formatter/src/ts/auxiliary/mapped_type_readonly_modifier_clause.rs index 87dcb6190d7..0083d1b55f5 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/mapped_type_readonly_modifier_clause.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/mapped_type_readonly_modifier_clause.rs @@ -1,22 +1,20 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsMappedTypeReadonlyModifierClause; use rome_js_syntax::TsMappedTypeReadonlyModifierClauseFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( + fn fmt_fields( node: &TsMappedTypeReadonlyModifierClause, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut JsFormatter, + ) -> FormatResult<()> { let TsMappedTypeReadonlyModifierClauseFields { operator_token, readonly_token, } = node.as_fields(); - formatted![ - formatter, - [operator_token.format(), readonly_token.format()] - ] + write![f, [operator_token.format(), readonly_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/method_signature_type_member.rs b/crates/rome_js_formatter/src/ts/auxiliary/method_signature_type_member.rs index ab3f451bbf2..947f2912e5e 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/method_signature_type_member.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/method_signature_type_member.rs @@ -1,13 +1,11 @@ use crate::prelude::*; -use crate::utils::format_type_member_separator; +use crate::utils::FormatTypeMemberSeparator; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsMethodSignatureTypeMember, TsMethodSignatureTypeMemberFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsMethodSignatureTypeMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsMethodSignatureTypeMember, f: &mut JsFormatter) -> FormatResult<()> { let TsMethodSignatureTypeMemberFields { name, optional_token, @@ -17,16 +15,15 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields(node: &TsModuleBlock, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &TsModuleBlock, f: &mut JsFormatter) -> FormatResult<()> { let TsModuleBlockFields { l_curly_token, items, r_curly_token, } = node.as_fields(); - formatter - .delimited( - &l_curly_token?, - formatted![formatter, [items.format()]]?, - &r_curly_token?, - ) - .block_indent() - .finish() + write!( + f, + [format_delimited(&l_curly_token?, &items.format(), &r_curly_token?,).block_indent()] + ) } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/named_tuple_type_element.rs b/crates/rome_js_formatter/src/ts/auxiliary/named_tuple_type_element.rs index 8922a80496e..1adb2bc41d7 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/named_tuple_type_element.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/named_tuple_type_element.rs @@ -1,12 +1,10 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsNamedTupleTypeElement, TsNamedTupleTypeElementFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsNamedTupleTypeElement, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsNamedTupleTypeElement, f: &mut JsFormatter) -> FormatResult<()> { let TsNamedTupleTypeElementFields { ty, question_mark_token, @@ -14,8 +12,8 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &TsOptionalPropertyAnnotation, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsOptionalPropertyAnnotation, f: &mut JsFormatter) -> FormatResult<()> { let TsOptionalPropertyAnnotationFields { question_mark_token, type_annotation, } = node.as_fields(); - formatted![ - formatter, - [question_mark_token.format(), type_annotation.format()] - ] + write![f, [question_mark_token.format(), type_annotation.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/optional_tuple_type_element.rs b/crates/rome_js_formatter/src/ts/auxiliary/optional_tuple_type_element.rs index 19ce191d39b..950f37d412a 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/optional_tuple_type_element.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/optional_tuple_type_element.rs @@ -1,18 +1,16 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsOptionalTupleTypeElement, TsOptionalTupleTypeElementFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsOptionalTupleTypeElement, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsOptionalTupleTypeElement, f: &mut JsFormatter) -> FormatResult<()> { let TsOptionalTupleTypeElementFields { ty, question_mark_token, } = node.as_fields(); let ty = ty.format(); let question_mark = question_mark_token.format(); - formatted![formatter, [ty, question_mark]] + write![f, [ty, question_mark]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/override_modifier.rs b/crates/rome_js_formatter/src/ts/auxiliary/override_modifier.rs index 4c6a2685620..f9680060d91 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/override_modifier.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/override_modifier.rs @@ -1,14 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsOverrideModifier; use rome_js_syntax::TsOverrideModifierFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsOverrideModifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsOverrideModifier, f: &mut JsFormatter) -> FormatResult<()> { let TsOverrideModifierFields { modifier_token } = node.as_fields(); - formatted![formatter, [modifier_token.format()]] + write![f, [modifier_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/property_signature_type_member.rs b/crates/rome_js_formatter/src/ts/auxiliary/property_signature_type_member.rs index e5a60d56383..f60dc9f3e45 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/property_signature_type_member.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/property_signature_type_member.rs @@ -1,15 +1,13 @@ use crate::prelude::*; -use crate::utils::{format_type_member_separator, FormatMemberName}; +use crate::utils::{FormatMemberName, FormatTypeMemberSeparator}; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsPropertySignatureTypeMember, TsPropertySignatureTypeMemberFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsPropertySignatureTypeMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsPropertySignatureTypeMember, f: &mut JsFormatter) -> FormatResult<()> { let TsPropertySignatureTypeMemberFields { readonly_token, name, @@ -18,17 +16,15 @@ impl FormatNodeFields separator_token, } = node.as_fields(); - let separator = format_type_member_separator(separator_token, formatter); - - formatted![ - formatter, + write![ + f, [ readonly_token.format(), space_token(), FormatMemberName::from(name?), optional_token.format(), type_annotation.format(), - separator + FormatTypeMemberSeparator::new(separator_token.as_ref()) ] ] } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/qualified_module_name.rs b/crates/rome_js_formatter/src/ts/auxiliary/qualified_module_name.rs index f9998f1be14..14f3520f291 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/qualified_module_name.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/qualified_module_name.rs @@ -1,22 +1,17 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsQualifiedModuleName; use rome_js_syntax::TsQualifiedModuleNameFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsQualifiedModuleName, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsQualifiedModuleName, f: &mut JsFormatter) -> FormatResult<()> { let TsQualifiedModuleNameFields { left, dot_token, right, } = node.as_fields(); - formatted![ - formatter, - [left.format(), dot_token.format(), right.format(),] - ] + write![f, [left.format(), dot_token.format(), right.format(),]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/qualified_name.rs b/crates/rome_js_formatter/src/ts/auxiliary/qualified_name.rs index 809a8c53d3e..2d162ec1e79 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/qualified_name.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/qualified_name.rs @@ -1,22 +1,17 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsQualifiedName; use rome_js_syntax::TsQualifiedNameFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsQualifiedName, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsQualifiedName, f: &mut JsFormatter) -> FormatResult<()> { let TsQualifiedNameFields { left, dot_token, right, } = node.as_fields(); - formatted![ - formatter, - [left.format(), dot_token.format(), right.format(),] - ] + write![f, [left.format(), dot_token.format(), right.format(),]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/readonly_modifier.rs b/crates/rome_js_formatter/src/ts/auxiliary/readonly_modifier.rs index f081ed8d2b3..c2b58013bc8 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/readonly_modifier.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/readonly_modifier.rs @@ -1,14 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsReadonlyModifier; use rome_js_syntax::TsReadonlyModifierFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsReadonlyModifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsReadonlyModifier, f: &mut JsFormatter) -> FormatResult<()> { let TsReadonlyModifierFields { modifier_token } = node.as_fields(); - formatted![formatter, [modifier_token.format()]] + write![f, [modifier_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/rest_tuple_type_element.rs b/crates/rome_js_formatter/src/ts/auxiliary/rest_tuple_type_element.rs index b10a0f10861..16b32da779d 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/rest_tuple_type_element.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/rest_tuple_type_element.rs @@ -1,18 +1,16 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsRestTupleTypeElement, TsRestTupleTypeElementFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsRestTupleTypeElement, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsRestTupleTypeElement, f: &mut JsFormatter) -> FormatResult<()> { let TsRestTupleTypeElementFields { dotdotdot_token, ty, } = node.as_fields(); let dotdotdot = dotdotdot_token.format(); let ty = ty.format(); - formatted![formatter, [dotdotdot, ty]] + write![f, [dotdotdot, ty]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/return_type_annotation.rs b/crates/rome_js_formatter/src/ts/auxiliary/return_type_annotation.rs index cd385758849..80a8b141b83 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/return_type_annotation.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/return_type_annotation.rs @@ -1,17 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsReturnTypeAnnotation; use rome_js_syntax::TsReturnTypeAnnotationFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsReturnTypeAnnotation, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsReturnTypeAnnotation, f: &mut JsFormatter) -> FormatResult<()> { let TsReturnTypeAnnotationFields { colon_token, ty } = node.as_fields(); - formatted![ - formatter, - [colon_token.format(), space_token(), ty.format()] - ] + write![f, [colon_token.format(), space_token(), ty.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/setter_signature_type_member.rs b/crates/rome_js_formatter/src/ts/auxiliary/setter_signature_type_member.rs index 63a814b91b0..f873d608fc6 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/setter_signature_type_member.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/setter_signature_type_member.rs @@ -1,13 +1,11 @@ use crate::prelude::*; -use crate::utils::format_type_member_separator; +use crate::utils::FormatTypeMemberSeparator; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsSetterSignatureTypeMember, TsSetterSignatureTypeMemberFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsSetterSignatureTypeMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsSetterSignatureTypeMember, f: &mut JsFormatter) -> FormatResult<()> { let TsSetterSignatureTypeMemberFields { set_token, name, @@ -17,23 +15,16 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &TsTypeAnnotation, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsTypeAnnotation, f: &mut JsFormatter) -> FormatResult<()> { let TsTypeAnnotationFields { colon_token, ty } = node.as_fields(); let colon = colon_token.format(); let ty = ty.format(); - formatted![formatter, [colon, space_token(), ty]] + write![f, [colon, space_token(), ty]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/type_constraint_clause.rs b/crates/rome_js_formatter/src/ts/auxiliary/type_constraint_clause.rs index 4a7f7678d27..debc18cd33c 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/type_constraint_clause.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/type_constraint_clause.rs @@ -1,16 +1,14 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsTypeConstraintClause, TsTypeConstraintClauseFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsTypeConstraintClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsTypeConstraintClause, f: &mut JsFormatter) -> FormatResult<()> { let TsTypeConstraintClauseFields { extends_token, ty } = node.as_fields(); let extends = extends_token.format(); let ty = ty.format(); - formatted![formatter, [extends, space_token(), ty]] + write![f, [extends, space_token(), ty]] } } diff --git a/crates/rome_js_formatter/src/ts/auxiliary/type_parameter_name.rs b/crates/rome_js_formatter/src/ts/auxiliary/type_parameter_name.rs index fd1cb180e73..70b9e8d26b9 100644 --- a/crates/rome_js_formatter/src/ts/auxiliary/type_parameter_name.rs +++ b/crates/rome_js_formatter/src/ts/auxiliary/type_parameter_name.rs @@ -1,14 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsTypeParameterName, TsTypeParameterNameFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsTypeParameterName, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsTypeParameterName, f: &mut JsFormatter) -> FormatResult<()> { let TsTypeParameterNameFields { ident_token } = node.as_fields(); - formatted![formatter, [ident_token.format()]] + write![f, [ident_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/bindings/identifier_binding.rs b/crates/rome_js_formatter/src/ts/bindings/identifier_binding.rs index 8ef58034ca6..50b11d3e9f5 100644 --- a/crates/rome_js_formatter/src/ts/bindings/identifier_binding.rs +++ b/crates/rome_js_formatter/src/ts/bindings/identifier_binding.rs @@ -1,14 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsIdentifierBinding, TsIdentifierBindingFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsIdentifierBinding, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsIdentifierBinding, f: &mut JsFormatter) -> FormatResult<()> { let TsIdentifierBindingFields { name_token } = node.as_fields(); - formatted![formatter, [name_token.format()]] + write![f, [name_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/bindings/index_signature_parameter.rs b/crates/rome_js_formatter/src/ts/bindings/index_signature_parameter.rs index bcd65f25f09..06fef99accf 100644 --- a/crates/rome_js_formatter/src/ts/bindings/index_signature_parameter.rs +++ b/crates/rome_js_formatter/src/ts/bindings/index_signature_parameter.rs @@ -1,12 +1,10 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsIndexSignatureParameter, TsIndexSignatureParameterFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsIndexSignatureParameter, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsIndexSignatureParameter, f: &mut JsFormatter) -> FormatResult<()> { let TsIndexSignatureParameterFields { binding, type_annotation, @@ -14,6 +12,6 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &TsPropertyParameter, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsPropertyParameter, f: &mut JsFormatter) -> FormatResult<()> { let TsPropertyParameterFields { modifiers, formal_parameter, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [modifiers.format(), space_token(), formal_parameter.format()] ] } diff --git a/crates/rome_js_formatter/src/ts/bindings/this_parameter.rs b/crates/rome_js_formatter/src/ts/bindings/this_parameter.rs index 2a05e21a7aa..da171c6a89f 100644 --- a/crates/rome_js_formatter/src/ts/bindings/this_parameter.rs +++ b/crates/rome_js_formatter/src/ts/bindings/this_parameter.rs @@ -1,17 +1,15 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsThisParameter, TsThisParameterFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsThisParameter, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsThisParameter, f: &mut JsFormatter) -> FormatResult<()> { let TsThisParameterFields { this_token, type_annotation, } = node.as_fields(); - formatted![formatter, [this_token.format(), type_annotation.format()]] + write![f, [this_token.format(), type_annotation.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/bindings/type_parameter.rs b/crates/rome_js_formatter/src/ts/bindings/type_parameter.rs index 1a850cb092d..ecd81cc4499 100644 --- a/crates/rome_js_formatter/src/ts/bindings/type_parameter.rs +++ b/crates/rome_js_formatter/src/ts/bindings/type_parameter.rs @@ -1,29 +1,26 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsTypeParameter, TsTypeParameterFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsTypeParameter, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsTypeParameter, f: &mut JsFormatter) -> FormatResult<()> { let TsTypeParameterFields { name, constraint, default, } = node.as_fields(); - formatted![ - formatter, - [ - name.format(), - constraint - .format() - .with_or_empty(|constraint| formatted![formatter, [space_token(), constraint]]), - default - .format() - .with_or_empty(|default| formatted![formatter, [space_token(), default]]) - ] - ] + write!(f, [name.format()])?; + + if let Some(constraint) = constraint { + write!(f, [space_token(), constraint.format()])?; + } + + if let Some(default) = default { + write!(f, [space_token(), default.format()])?; + } + + Ok(()) } } diff --git a/crates/rome_js_formatter/src/ts/bindings/type_parameters.rs b/crates/rome_js_formatter/src/ts/bindings/type_parameters.rs index d1e6512e6e8..e36b1f1dd74 100644 --- a/crates/rome_js_formatter/src/ts/bindings/type_parameters.rs +++ b/crates/rome_js_formatter/src/ts/bindings/type_parameters.rs @@ -1,25 +1,22 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsTypeParameters, TsTypeParametersFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsTypeParameters, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsTypeParameters, f: &mut JsFormatter) -> FormatResult<()> { let TsTypeParametersFields { items, r_angle_token, l_angle_token, } = node.as_fields(); - formatter - .delimited( - &l_angle_token?, - formatted![formatter, [items.format()]]?, - &r_angle_token?, - ) - .soft_block_indent() - .finish() + write!( + f, + [ + format_delimited(&l_angle_token?, &items.format(), &r_angle_token?,) + .soft_block_indent() + ] + ) } } diff --git a/crates/rome_js_formatter/src/ts/classes/constructor_signature_class_member.rs b/crates/rome_js_formatter/src/ts/classes/constructor_signature_class_member.rs index 844814b770b..303ce39d69c 100644 --- a/crates/rome_js_formatter/src/ts/classes/constructor_signature_class_member.rs +++ b/crates/rome_js_formatter/src/ts/classes/constructor_signature_class_member.rs @@ -1,16 +1,17 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::TsConstructorSignatureClassMember; use rome_js_syntax::TsConstructorSignatureClassMemberFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( + fn fmt_fields( node: &TsConstructorSignatureClassMember, - formatter: &JsFormatter, - ) -> FormatResult { + f: &mut JsFormatter, + ) -> FormatResult<()> { let TsConstructorSignatureClassMemberFields { modifiers, name, @@ -18,18 +19,17 @@ impl FormatNodeFields semicolon_token, } = node.as_fields(); - format_with_semicolon( - formatter, - formatted![ - formatter, - [ + write!( + f, + [FormatWithSemicolon::new( + &format_args!( modifiers.format(), space_token(), name.format(), parameters.format(), - ] - ]?, - semicolon_token, + ), + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/ts/classes/extends_clause.rs b/crates/rome_js_formatter/src/ts/classes/extends_clause.rs index 6dda4b34f65..1b4375ddd00 100644 --- a/crates/rome_js_formatter/src/ts/classes/extends_clause.rs +++ b/crates/rome_js_formatter/src/ts/classes/extends_clause.rs @@ -1,12 +1,10 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{TsExtendsClause, TsExtendsClauseFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsExtendsClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsExtendsClause, f: &mut JsFormatter) -> FormatResult<()> { let TsExtendsClauseFields { extends_token, types, @@ -15,22 +13,16 @@ impl FormatNodeFields for FormatNodeRule { let extends_token = extends_token.format().memoized(); let types = types.format().memoized(); - Ok(group_elements(formatted![ - formatter, - [ - if_group_breaks(block_indent(formatted![ - formatter, - [ - &extends_token, - space_token(), - soft_block_indent(formatted![formatter, [&types]]?) - ] - ]?)), - if_group_fits_on_single_line(formatted![ - formatter, - [&extends_token, space_token(), &types] - ]?), - ] - ]?)) + write!( + f, + [group_elements(&format_args!( + if_group_breaks(&block_indent(&format_args![ + &extends_token, + space_token(), + soft_block_indent(&types) + ])), + if_group_fits_on_line(&format_args![&extends_token, space_token(), &types]), + ))] + ) } } diff --git a/crates/rome_js_formatter/src/ts/classes/getter_signature_class_member.rs b/crates/rome_js_formatter/src/ts/classes/getter_signature_class_member.rs index fa8686c6c7f..87aab4232ba 100644 --- a/crates/rome_js_formatter/src/ts/classes/getter_signature_class_member.rs +++ b/crates/rome_js_formatter/src/ts/classes/getter_signature_class_member.rs @@ -1,15 +1,14 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use rome_formatter::{format_args, write}; + +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; use rome_js_syntax::{TsGetterSignatureClassMember, TsGetterSignatureClassMemberFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsGetterSignatureClassMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsGetterSignatureClassMember, f: &mut JsFormatter) -> FormatResult<()> { let TsGetterSignatureClassMemberFields { modifiers, get_token, @@ -20,11 +19,10 @@ impl FormatNodeFields semicolon_token, } = node.as_fields(); - format_with_semicolon( - formatter, - formatted![ - formatter, - [ + write!( + f, + [FormatWithSemicolon::new( + &format_args!( modifiers.format(), space_token(), get_token.format(), @@ -33,9 +31,9 @@ impl FormatNodeFields l_paren_token.format(), r_paren_token.format(), return_type.format(), - ] - ]?, - semicolon_token, + ), + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/ts/classes/index_signature_class_member.rs b/crates/rome_js_formatter/src/ts/classes/index_signature_class_member.rs index e09dfc6ed56..9600ecdabc5 100644 --- a/crates/rome_js_formatter/src/ts/classes/index_signature_class_member.rs +++ b/crates/rome_js_formatter/src/ts/classes/index_signature_class_member.rs @@ -1,14 +1,12 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::TsIndexSignatureClassMember; use rome_js_syntax::TsIndexSignatureClassMemberFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsIndexSignatureClassMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsIndexSignatureClassMember, f: &mut JsFormatter) -> FormatResult<()> { let TsIndexSignatureClassMemberFields { modifiers, l_brack_token, @@ -18,20 +16,19 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &TsMethodSignatureClassMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsMethodSignatureClassMember, f: &mut JsFormatter) -> FormatResult<()> { let TsMethodSignatureClassMemberFields { modifiers, async_token, @@ -21,24 +19,23 @@ impl FormatNodeFields semicolon_token, } = node.as_fields(); - format_with_semicolon( - formatter, - formatted![ - formatter, - [ + write!( + f, + [FormatWithSemicolon::new( + &format_args!( modifiers.format(), async_token .format() - .with_or_empty(|token| formatted![formatter, [token, space_token()]]), + .with_or_empty(|token, f| write![f, [token, space_token()]]), space_token(), FormatMemberName::from(name?), question_mark_token.format(), type_parameters.format(), parameters.format(), return_type_annotation.format(), - ] - ]?, - semicolon_token, + ), + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/ts/classes/property_signature_class_member.rs b/crates/rome_js_formatter/src/ts/classes/property_signature_class_member.rs index c87f1b41f2c..0bdbc620a07 100644 --- a/crates/rome_js_formatter/src/ts/classes/property_signature_class_member.rs +++ b/crates/rome_js_formatter/src/ts/classes/property_signature_class_member.rs @@ -1,15 +1,14 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use rome_formatter::{format_args, write}; + +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; use rome_js_syntax::{TsPropertySignatureClassMember, TsPropertySignatureClassMemberFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsPropertySignatureClassMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsPropertySignatureClassMember, f: &mut JsFormatter) -> FormatResult<()> { let TsPropertySignatureClassMemberFields { modifiers, name, @@ -17,18 +16,17 @@ impl FormatNodeFields semicolon_token, } = node.as_fields(); - format_with_semicolon( - formatter, - formatted![ - formatter, - [ + write!( + f, + [FormatWithSemicolon::new( + &format_args!( modifiers.format(), space_token(), name.format(), property_annotation.format(), - ] - ]?, - semicolon_token, + ), + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/ts/classes/setter_signature_class_member.rs b/crates/rome_js_formatter/src/ts/classes/setter_signature_class_member.rs index f40351ff9f3..434405e21fa 100644 --- a/crates/rome_js_formatter/src/ts/classes/setter_signature_class_member.rs +++ b/crates/rome_js_formatter/src/ts/classes/setter_signature_class_member.rs @@ -1,15 +1,13 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{TsSetterSignatureClassMember, TsSetterSignatureClassMemberFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsSetterSignatureClassMember, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsSetterSignatureClassMember, f: &mut JsFormatter) -> FormatResult<()> { let TsSetterSignatureClassMemberFields { modifiers, set_token, @@ -20,28 +18,21 @@ impl FormatNodeFields semicolon_token, } = node.as_fields(); - let set_token = set_token.format(); - let name = name.format(); - let l_paren_token = l_paren_token.format(); - let parameters = parameter.format(); - let r_paren_token = r_paren_token.format(); - - format_with_semicolon( - formatter, - formatted![ - formatter, - [ + write!( + f, + [FormatWithSemicolon::new( + &format_args!( modifiers.format(), space_token(), - set_token, + set_token.format(), space_token(), - name, - l_paren_token, - parameters, - r_paren_token, - ] - ]?, - semicolon_token, + name.format(), + l_paren_token.format(), + parameter.format(), + r_paren_token.format(), + ), + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/ts/declarations/declare_function_declaration.rs b/crates/rome_js_formatter/src/ts/declarations/declare_function_declaration.rs index 72855f8aec1..cc5178d2356 100644 --- a/crates/rome_js_formatter/src/ts/declarations/declare_function_declaration.rs +++ b/crates/rome_js_formatter/src/ts/declarations/declare_function_declaration.rs @@ -1,16 +1,14 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsDeclareFunctionDeclaration; use rome_js_syntax::TsDeclareFunctionDeclarationFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsDeclareFunctionDeclaration, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsDeclareFunctionDeclaration, f: &mut JsFormatter) -> FormatResult<()> { let TsDeclareFunctionDeclarationFields { async_token, function_token, @@ -21,15 +19,14 @@ impl FormatNodeFields semicolon_token, } = node.as_fields(); - format_with_semicolon( - formatter, - formatted![ - formatter, + let declaration = format_with(|f| { + if let Some(async_token) = &async_token { + write!(f, [async_token.format(), space_token()])?; + } + + write!( + f, [ - async_token.format().with_or_empty(|async_token| formatted![ - formatter, - [async_token, space_token()] - ]), function_token.format(), space_token(), id.format(), @@ -37,8 +34,15 @@ impl FormatNodeFields parameters.format(), return_type_annotation.format(), ] - ]?, - semicolon_token, + ) + }); + + write!( + f, + [FormatWithSemicolon::new( + &declaration, + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/ts/declarations/enum_declaration.rs b/crates/rome_js_formatter/src/ts/declarations/enum_declaration.rs index ee6f4071d00..f319ab8d70a 100644 --- a/crates/rome_js_formatter/src/ts/declarations/enum_declaration.rs +++ b/crates/rome_js_formatter/src/ts/declarations/enum_declaration.rs @@ -1,14 +1,11 @@ use crate::prelude::*; -use crate::utils::has_leading_newline; +use rome_formatter::write; + use crate::FormatNodeFields; use rome_js_syntax::{TsEnumDeclaration, TsEnumDeclarationFields}; -use rome_rowan::AstNode; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsEnumDeclaration, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsEnumDeclaration, f: &mut JsFormatter) -> FormatResult<()> { let TsEnumDeclarationFields { const_token, enum_token, @@ -18,37 +15,20 @@ impl FormatNodeFields for FormatNodeRule { r_curly_token, } = node.as_fields(); - let has_newline = has_leading_newline(members.syntax()); - let list = formatter - .delimited( - &l_curly_token?, - join_elements( - if has_newline { - hard_line_break() - } else { - soft_line_break_or_space() - }, - formatter.format_separated(&members, || token(","))?, - ), - &r_curly_token?, - ) - .soft_block_spaces() - .finish()?; + if let Some(const_token) = const_token { + write!(f, [const_token.format(), space_token()])?; + } - formatted![ - formatter, + write!( + f, [ - const_token.format().with_or_empty(|const_token| formatted![ - formatter, - [const_token, space_token()] - ]), - enum_token - .format() - .with(|enum_token| formatted![formatter, [enum_token, space_token()]]), - id.format() - .with(|id| formatted![formatter, [id, space_token()]]), - list + enum_token.format(), + space_token(), + id.format(), + space_token(), + format_delimited(&l_curly_token?, &members.format(), &r_curly_token?,) + .soft_block_spaces() ] - ] + ) } } diff --git a/crates/rome_js_formatter/src/ts/declarations/external_module_declaration.rs b/crates/rome_js_formatter/src/ts/declarations/external_module_declaration.rs index 3774679182d..b4bfb04f311 100644 --- a/crates/rome_js_formatter/src/ts/declarations/external_module_declaration.rs +++ b/crates/rome_js_formatter/src/ts/declarations/external_module_declaration.rs @@ -1,21 +1,20 @@ use crate::prelude::*; +use rome_formatter::write; + use crate::FormatNodeFields; use rome_js_syntax::TsExternalModuleDeclaration; use rome_js_syntax::TsExternalModuleDeclarationFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsExternalModuleDeclaration, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsExternalModuleDeclaration, f: &mut JsFormatter) -> FormatResult<()> { let TsExternalModuleDeclarationFields { body, module_token, source, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ module_token.format(), space_token(), diff --git a/crates/rome_js_formatter/src/ts/declarations/global_declaration.rs b/crates/rome_js_formatter/src/ts/declarations/global_declaration.rs index 4f980e3e97d..a898dda17f5 100644 --- a/crates/rome_js_formatter/src/ts/declarations/global_declaration.rs +++ b/crates/rome_js_formatter/src/ts/declarations/global_declaration.rs @@ -1,18 +1,14 @@ use crate::prelude::*; +use rome_formatter::write; + use crate::FormatNodeFields; use rome_js_syntax::TsGlobalDeclaration; use rome_js_syntax::TsGlobalDeclarationFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsGlobalDeclaration, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsGlobalDeclaration, f: &mut JsFormatter) -> FormatResult<()> { let TsGlobalDeclarationFields { global_token, body } = node.as_fields(); - formatted![ - formatter, - [global_token.format(), space_token(), body.format()] - ] + write![f, [global_token.format(), space_token(), body.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/declarations/import_equals_declaration.rs b/crates/rome_js_formatter/src/ts/declarations/import_equals_declaration.rs index d012518cdbf..f6430612804 100644 --- a/crates/rome_js_formatter/src/ts/declarations/import_equals_declaration.rs +++ b/crates/rome_js_formatter/src/ts/declarations/import_equals_declaration.rs @@ -1,14 +1,12 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::TsImportEqualsDeclaration; use rome_js_syntax::TsImportEqualsDeclarationFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsImportEqualsDeclaration, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsImportEqualsDeclaration, f: &mut JsFormatter) -> FormatResult<()> { let TsImportEqualsDeclarationFields { import_token, type_token, @@ -18,24 +16,23 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &TsInterfaceDeclaration, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsInterfaceDeclaration, f: &mut JsFormatter) -> FormatResult<()> { let TsInterfaceDeclarationFields { interface_token, id, @@ -17,27 +16,27 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &TsModuleDeclaration, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsModuleDeclaration, f: &mut JsFormatter) -> FormatResult<()> { let TsModuleDeclarationFields { module_or_namespace, name, body, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ module_or_namespace.format(), space_token(), diff --git a/crates/rome_js_formatter/src/ts/declarations/type_alias_declaration.rs b/crates/rome_js_formatter/src/ts/declarations/type_alias_declaration.rs index 6755e425aa3..e0566175a66 100644 --- a/crates/rome_js_formatter/src/ts/declarations/type_alias_declaration.rs +++ b/crates/rome_js_formatter/src/ts/declarations/type_alias_declaration.rs @@ -1,13 +1,11 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{TsTypeAliasDeclaration, TsTypeAliasDeclarationFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsTypeAliasDeclaration, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsTypeAliasDeclaration, f: &mut JsFormatter) -> FormatResult<()> { let TsTypeAliasDeclarationFields { type_token, binding_identifier, @@ -17,11 +15,10 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &TsAsExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsAsExpression, f: &mut JsFormatter) -> FormatResult<()> { let TsAsExpressionFields { ty, as_token, expression, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ expression.format(), space_token(), diff --git a/crates/rome_js_formatter/src/ts/expressions/name_with_type_arguments.rs b/crates/rome_js_formatter/src/ts/expressions/name_with_type_arguments.rs index b7f4cfcaa38..79fffbb7614 100644 --- a/crates/rome_js_formatter/src/ts/expressions/name_with_type_arguments.rs +++ b/crates/rome_js_formatter/src/ts/expressions/name_with_type_arguments.rs @@ -1,17 +1,15 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsNameWithTypeArguments, TsNameWithTypeArgumentsFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsNameWithTypeArguments, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsNameWithTypeArguments, f: &mut JsFormatter) -> FormatResult<()> { let TsNameWithTypeArgumentsFields { name, type_arguments, } = node.as_fields(); - formatted![formatter, [name.format(), type_arguments.format()]] + write![f, [name.format(), type_arguments.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/expressions/non_null_assertion_expression.rs b/crates/rome_js_formatter/src/ts/expressions/non_null_assertion_expression.rs index 90a541ec0d4..cede60d891f 100644 --- a/crates/rome_js_formatter/src/ts/expressions/non_null_assertion_expression.rs +++ b/crates/rome_js_formatter/src/ts/expressions/non_null_assertion_expression.rs @@ -1,20 +1,18 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsNonNullAssertionExpression; use rome_js_syntax::TsNonNullAssertionExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsNonNullAssertionExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsNonNullAssertionExpression, f: &mut JsFormatter) -> FormatResult<()> { let TsNonNullAssertionExpressionFields { expression, excl_token, } = node.as_fields(); - formatted![formatter, [expression.format(), excl_token.format()]] + write![f, [expression.format(), excl_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/expressions/template_chunk_element.rs b/crates/rome_js_formatter/src/ts/expressions/template_chunk_element.rs index 54595a54a03..13c637290a3 100644 --- a/crates/rome_js_formatter/src/ts/expressions/template_chunk_element.rs +++ b/crates/rome_js_formatter/src/ts/expressions/template_chunk_element.rs @@ -4,10 +4,7 @@ use crate::FormatNodeFields; use rome_js_syntax::{TsTemplateChunkElement, TsTemplateChunkElementFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsTemplateChunkElement, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsTemplateChunkElement, formatter: &mut JsFormatter) -> FormatResult<()> { let TsTemplateChunkElementFields { template_chunk_token, } = node.as_fields(); diff --git a/crates/rome_js_formatter/src/ts/expressions/template_element.rs b/crates/rome_js_formatter/src/ts/expressions/template_element.rs index efef8dec4da..cc2aa2f4b8a 100644 --- a/crates/rome_js_formatter/src/ts/expressions/template_element.rs +++ b/crates/rome_js_formatter/src/ts/expressions/template_element.rs @@ -4,10 +4,7 @@ use crate::FormatNodeFields; use rome_js_syntax::TsTemplateElement; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsTemplateElement, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsTemplateElement, formatter: &mut JsFormatter) -> FormatResult<()> { format_template_literal(TemplateElement::Ts(node.clone()), formatter) } } diff --git a/crates/rome_js_formatter/src/ts/expressions/template_literal_type.rs b/crates/rome_js_formatter/src/ts/expressions/template_literal_type.rs index b7a20aa71d4..6349fd8753f 100644 --- a/crates/rome_js_formatter/src/ts/expressions/template_literal_type.rs +++ b/crates/rome_js_formatter/src/ts/expressions/template_literal_type.rs @@ -1,21 +1,19 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsTemplateLiteralType; use rome_js_syntax::TsTemplateLiteralTypeFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsTemplateLiteralType, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsTemplateLiteralType, f: &mut JsFormatter) -> FormatResult<()> { let TsTemplateLiteralTypeFields { l_tick_token, elements, r_tick_token, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ l_tick_token.format(), elements.format(), diff --git a/crates/rome_js_formatter/src/ts/expressions/type_arguments.rs b/crates/rome_js_formatter/src/ts/expressions/type_arguments.rs index 73d84f677e1..2e9483830c8 100644 --- a/crates/rome_js_formatter/src/ts/expressions/type_arguments.rs +++ b/crates/rome_js_formatter/src/ts/expressions/type_arguments.rs @@ -1,25 +1,24 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsTypeArguments, TsTypeArgumentsFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsTypeArguments, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsTypeArguments, f: &mut JsFormatter) -> FormatResult<()> { let TsTypeArgumentsFields { l_angle_token, ts_type_argument_list, r_angle_token, } = node.as_fields(); - formatter - .delimited( + write!( + f, + [format_delimited( &l_angle_token?, - formatted![formatter, [ts_type_argument_list.format()]]?, + &ts_type_argument_list.format(), &r_angle_token?, ) - .soft_block_indent() - .finish() + .soft_block_indent()] + ) } } diff --git a/crates/rome_js_formatter/src/ts/expressions/type_assertion_expression.rs b/crates/rome_js_formatter/src/ts/expressions/type_assertion_expression.rs index d2fb1611b64..4eebaf09bda 100644 --- a/crates/rome_js_formatter/src/ts/expressions/type_assertion_expression.rs +++ b/crates/rome_js_formatter/src/ts/expressions/type_assertion_expression.rs @@ -1,13 +1,11 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsTypeAssertionExpression; use rome_js_syntax::TsTypeAssertionExpressionFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsTypeAssertionExpression, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsTypeAssertionExpression, f: &mut JsFormatter) -> FormatResult<()> { let TsTypeAssertionExpressionFields { l_angle_token, ty, @@ -15,17 +13,11 @@ impl FormatNodeFields for FormatNodeRule for FormatTsEnumMemberList { type Context = JsFormatContext; - fn format(node: &TsEnumMemberList, formatter: &JsFormatter) -> FormatResult { - Ok(join_elements( - soft_line_break_or_space(), - formatter.format_separated(node, || token(","))?, - )) + fn fmt(node: &TsEnumMemberList, f: &mut JsFormatter) -> FormatResult<()> { + let has_newline = has_leading_newline(node.syntax()); + + f.join_with(&if has_newline { + hard_line_break() + } else { + soft_line_break_or_space() + }) + .entries(node.format_separated(token(","))) + .finish() } } diff --git a/crates/rome_js_formatter/src/ts/lists/index_signature_modifier_list.rs b/crates/rome_js_formatter/src/ts/lists/index_signature_modifier_list.rs index 9e6fabfe346..5071be57176 100644 --- a/crates/rome_js_formatter/src/ts/lists/index_signature_modifier_list.rs +++ b/crates/rome_js_formatter/src/ts/lists/index_signature_modifier_list.rs @@ -1,18 +1,15 @@ use crate::generated::FormatTsIndexSignatureModifierList; use crate::prelude::*; use crate::utils::sort_modifiers_by_precedence; + use rome_js_syntax::TsIndexSignatureModifierList; impl FormatRule for FormatTsIndexSignatureModifierList { type Context = JsFormatContext; - fn format( - node: &TsIndexSignatureModifierList, - formatter: &JsFormatter, - ) -> FormatResult { - Ok(join_elements( - space_token(), - formatter.format_all(sort_modifiers_by_precedence(node).into_iter().formatted())?, - )) + fn fmt(node: &TsIndexSignatureModifierList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&space_token()) + .entries(sort_modifiers_by_precedence(node).into_iter().formatted()) + .finish() } } diff --git a/crates/rome_js_formatter/src/ts/lists/intersection_type_element_list.rs b/crates/rome_js_formatter/src/ts/lists/intersection_type_element_list.rs index bcd97b66514..14e296f82f9 100644 --- a/crates/rome_js_formatter/src/ts/lists/intersection_type_element_list.rs +++ b/crates/rome_js_formatter/src/ts/lists/intersection_type_element_list.rs @@ -1,48 +1,24 @@ use crate::generated::FormatTsIntersectionTypeElementList; use crate::prelude::*; +use crate::ts::lists::union_type_variant_list::FormatTypeVariant; use rome_js_syntax::TsIntersectionTypeElementList; use rome_rowan::AstSeparatedList; impl FormatRule for FormatTsIntersectionTypeElementList { type Context = JsFormatContext; - fn format( - node: &TsIntersectionTypeElementList, - formatter: &JsFormatter, - ) -> FormatResult { - let mut elements = Vec::with_capacity(node.len()); + fn fmt(node: &TsIntersectionTypeElementList, f: &mut JsFormatter) -> FormatResult<()> { let last_index = node.len().saturating_sub(1); - for (index, item) in node.elements().enumerate() { - let ty = formatted![formatter, [item.node().format()]]?; - let separator = item.trailing_separator()?; - - let separator = match separator { - Some(token) => { - if index == last_index { - formatter.format_replaced(token, empty_element()) - } else { - formatted![ - formatter, - [soft_line_break_or_space(), token.format(), space_token()] - ]? - } - } - None => { - if index == last_index { - empty_element() - } else { - formatted![ - formatter, - [soft_line_break_or_space(), token("&"), space_token()] - ]? - } - } - }; - - elements.push(format_elements![group_elements(ty), separator]); - } - - Ok(concat_elements(elements)) + f.join() + .entries( + node.elements() + .enumerate() + .map(|(index, item)| FormatTypeVariant { + last: index == last_index, + element: item, + }), + ) + .finish() } } diff --git a/crates/rome_js_formatter/src/ts/lists/method_signature_modifier_list.rs b/crates/rome_js_formatter/src/ts/lists/method_signature_modifier_list.rs index cf0c6084eec..9afc7a2a12a 100644 --- a/crates/rome_js_formatter/src/ts/lists/method_signature_modifier_list.rs +++ b/crates/rome_js_formatter/src/ts/lists/method_signature_modifier_list.rs @@ -6,13 +6,9 @@ use rome_js_syntax::TsMethodSignatureModifierList; impl FormatRule for FormatTsMethodSignatureModifierList { type Context = JsFormatContext; - fn format( - node: &TsMethodSignatureModifierList, - formatter: &JsFormatter, - ) -> FormatResult { - Ok(join_elements( - space_token(), - formatter.format_all(sort_modifiers_by_precedence(node).into_iter().formatted())?, - )) + fn fmt(node: &TsMethodSignatureModifierList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&space_token()) + .entries(sort_modifiers_by_precedence(node).into_iter().formatted()) + .finish() } } diff --git a/crates/rome_js_formatter/src/ts/lists/property_parameter_modifier_list.rs b/crates/rome_js_formatter/src/ts/lists/property_parameter_modifier_list.rs index 93931f07f21..34a5ce7e8a1 100644 --- a/crates/rome_js_formatter/src/ts/lists/property_parameter_modifier_list.rs +++ b/crates/rome_js_formatter/src/ts/lists/property_parameter_modifier_list.rs @@ -6,13 +6,9 @@ use rome_js_syntax::TsPropertyParameterModifierList; impl FormatRule for FormatTsPropertyParameterModifierList { type Context = JsFormatContext; - fn format( - node: &TsPropertyParameterModifierList, - formatter: &JsFormatter, - ) -> FormatResult { - Ok(join_elements( - space_token(), - formatter.format_all(sort_modifiers_by_precedence(node).into_iter().formatted())?, - )) + fn fmt(node: &TsPropertyParameterModifierList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&space_token()) + .entries(sort_modifiers_by_precedence(node).into_iter().formatted()) + .finish() } } diff --git a/crates/rome_js_formatter/src/ts/lists/property_signature_modifier_list.rs b/crates/rome_js_formatter/src/ts/lists/property_signature_modifier_list.rs index b3323a5a977..3bf2d560763 100644 --- a/crates/rome_js_formatter/src/ts/lists/property_signature_modifier_list.rs +++ b/crates/rome_js_formatter/src/ts/lists/property_signature_modifier_list.rs @@ -6,13 +6,9 @@ use rome_js_syntax::TsPropertySignatureModifierList; impl FormatRule for FormatTsPropertySignatureModifierList { type Context = JsFormatContext; - fn format( - node: &TsPropertySignatureModifierList, - formatter: &JsFormatter, - ) -> FormatResult { - Ok(join_elements( - space_token(), - formatter.format_all(sort_modifiers_by_precedence(node).into_iter().formatted())?, - )) + fn fmt(node: &TsPropertySignatureModifierList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&space_token()) + .entries(sort_modifiers_by_precedence(node).into_iter().formatted()) + .finish() } } diff --git a/crates/rome_js_formatter/src/ts/lists/template_element_list.rs b/crates/rome_js_formatter/src/ts/lists/template_element_list.rs index a70379e72e3..99dd72b93c0 100644 --- a/crates/rome_js_formatter/src/ts/lists/template_element_list.rs +++ b/crates/rome_js_formatter/src/ts/lists/template_element_list.rs @@ -1,19 +1,17 @@ use crate::generated::FormatTsTemplateElementList; use crate::prelude::*; use rome_js_syntax::TsTemplateElementList; -use rome_rowan::AstNodeList; impl FormatRule for FormatTsTemplateElementList { type Context = JsFormatContext; - fn format( - node: &TsTemplateElementList, - formatter: &JsFormatter, - ) -> FormatResult { - Ok(concat_elements( - formatter - .format_all(node.iter().formatted())? - .map(group_elements), - )) + fn fmt(node: &TsTemplateElementList, f: &mut JsFormatter) -> FormatResult<()> { + let mut join = f.join(); + + for item in node { + join.entry(&group_elements(&item.format())); + } + + join.finish() } } diff --git a/crates/rome_js_formatter/src/ts/lists/tuple_type_element_list.rs b/crates/rome_js_formatter/src/ts/lists/tuple_type_element_list.rs index 69e4d29dd59..3c89f38c283 100644 --- a/crates/rome_js_formatter/src/ts/lists/tuple_type_element_list.rs +++ b/crates/rome_js_formatter/src/ts/lists/tuple_type_element_list.rs @@ -5,13 +5,9 @@ use rome_js_syntax::TsTupleTypeElementList; impl FormatRule for FormatTsTupleTypeElementList { type Context = JsFormatContext; - fn format( - node: &TsTupleTypeElementList, - formatter: &JsFormatter, - ) -> FormatResult { - Ok(join_elements( - soft_line_break_or_space(), - formatter.format_separated(node, || token(","))?, - )) + fn fmt(node: &TsTupleTypeElementList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&soft_line_break_or_space()) + .entries(node.format_separated(token(","))) + .finish() } } diff --git a/crates/rome_js_formatter/src/ts/lists/type_argument_list.rs b/crates/rome_js_formatter/src/ts/lists/type_argument_list.rs index 045effad023..7bca496745a 100644 --- a/crates/rome_js_formatter/src/ts/lists/type_argument_list.rs +++ b/crates/rome_js_formatter/src/ts/lists/type_argument_list.rs @@ -1,4 +1,3 @@ -use crate::formatter::{FormatSeparatedOptions, TrailingSeparator}; use crate::generated::FormatTsTypeArgumentList; use crate::prelude::*; use rome_js_syntax::TsTypeArgumentList; @@ -6,15 +5,14 @@ use rome_js_syntax::TsTypeArgumentList; impl FormatRule for FormatTsTypeArgumentList { type Context = JsFormatContext; - fn format(node: &TsTypeArgumentList, formatter: &JsFormatter) -> FormatResult { - Ok(join_elements( - soft_line_break_or_space(), - formatter.format_separated_with_options( - node, - || token(","), - FormatSeparatedOptions::default() - .with_trailing_separator(TrailingSeparator::Disallowed), - )?, - )) + fn fmt(node: &TsTypeArgumentList, f: &mut JsFormatter) -> FormatResult<()> { + f.join_with(&soft_line_break_or_space()) + .entries( + node.format_separated(token(",")).with_options( + FormatSeparatedOptions::default() + .with_trailing_separator(TrailingSeparator::Disallowed), + ), + ) + .finish() } } diff --git a/crates/rome_js_formatter/src/ts/lists/type_list.rs b/crates/rome_js_formatter/src/ts/lists/type_list.rs index abb5903906a..2ca5ca8fec8 100644 --- a/crates/rome_js_formatter/src/ts/lists/type_list.rs +++ b/crates/rome_js_formatter/src/ts/lists/type_list.rs @@ -1,4 +1,3 @@ -use crate::formatter::{FormatSeparatedOptions, TrailingSeparator}; use crate::generated::FormatTsTypeList; use crate::prelude::*; use rome_js_syntax::TsTypeList; @@ -6,16 +5,15 @@ use rome_js_syntax::TsTypeList; impl FormatRule for FormatTsTypeList { type Context = JsFormatContext; - fn format(node: &TsTypeList, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &TsTypeList, f: &mut JsFormatter) -> FormatResult<()> { // the grouping will be applied by the parent - Ok(join_elements( - soft_line_break_or_space(), - formatter.format_separated_with_options( - node, - || token(","), - FormatSeparatedOptions::default() - .with_trailing_separator(TrailingSeparator::Disallowed), - )?, - )) + f.join_with(&soft_line_break_or_space()) + .entries( + node.format_separated(token(",")).with_options( + FormatSeparatedOptions::default() + .with_trailing_separator(TrailingSeparator::Disallowed), + ), + ) + .finish() } } diff --git a/crates/rome_js_formatter/src/ts/lists/type_member_list.rs b/crates/rome_js_formatter/src/ts/lists/type_member_list.rs index 9fc6d21509c..986fe598cc5 100644 --- a/crates/rome_js_formatter/src/ts/lists/type_member_list.rs +++ b/crates/rome_js_formatter/src/ts/lists/type_member_list.rs @@ -1,44 +1,61 @@ use crate::generated::FormatTsTypeMemberList; use crate::prelude::*; -use rome_js_syntax::TsTypeMemberList; +use rome_formatter::{write, Buffer, VecBuffer}; +use rome_js_syntax::{TsAnyTypeMember, TsTypeMemberList}; + use rome_rowan::AstNodeList; impl FormatRule for FormatTsTypeMemberList { type Context = JsFormatContext; - fn format(node: &TsTypeMemberList, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &TsTypeMemberList, f: &mut JsFormatter) -> FormatResult<()> { let items = node.iter(); let last_index = items.len().saturating_sub(1); - let items = items - .enumerate() - .map(|(index, element)| { - let formatted_element = formatted![formatter, [element.format()]]?; - - let is_verbatim = matches!( - formatted_element.last_element(), - Some(FormatElement::Verbatim(_)) - ); - - let separator = if !is_verbatim { - // Children don't format the separator on purpose, so it's up to the parent - this node, - // to decide to print their separator - if index == last_index { - if_group_breaks(token(";")) - } else { - token(";") - } - } else { - empty_element() - }; - - Ok(format_elements![ - group_elements(formatted_element), - separator - ]) - }) - .collect::>>()?; - - Ok(join_elements(soft_line_break_or_space(), items)) + f.join_with(&soft_line_break_or_space()) + .entries(items.enumerate().map(|(index, member)| TsTypeMemberItem { + last: index == last_index, + member, + })) + .finish() + } +} + +struct TsTypeMemberItem { + last: bool, + member: TsAnyTypeMember, +} + +impl Format for TsTypeMemberItem { + fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> { + let mut buffer = VecBuffer::new(f.state_mut()); + + write!(buffer, [self.member.format()])?; + + let formatted_element = buffer.into_element(); + + let is_verbatim = matches!( + formatted_element.last_element(), + Some(FormatElement::Verbatim(_)) + ); + + write!( + f, + [group_elements(&format_once(|f| { + f.write_element(formatted_element) + }))] + )?; + + if !is_verbatim { + // Children don't format the separator on purpose, so it's up to the parent - this node, + // to decide to print their separator + if self.last { + write!(f, [if_group_breaks(&token(";"))])?; + } else { + write!(f, [token(";")])?; + } + } + + Ok(()) } } diff --git a/crates/rome_js_formatter/src/ts/lists/type_parameter_list.rs b/crates/rome_js_formatter/src/ts/lists/type_parameter_list.rs index faca23cf2e0..35634b85dd9 100644 --- a/crates/rome_js_formatter/src/ts/lists/type_parameter_list.rs +++ b/crates/rome_js_formatter/src/ts/lists/type_parameter_list.rs @@ -1,4 +1,3 @@ -use crate::formatter::{FormatSeparatedOptions, TrailingSeparator}; use crate::generated::FormatTsTypeParameterList; use crate::prelude::*; use rome_js_syntax::TsTypeParameterList; @@ -7,7 +6,7 @@ use rome_rowan::AstSeparatedList; impl FormatRule for FormatTsTypeParameterList { type Context = JsFormatContext; - fn format(node: &TsTypeParameterList, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &TsTypeParameterList, f: &mut JsFormatter) -> FormatResult<()> { // nodes and formatter are not aware of the source type (TSX vs TS), which means we can't // exactly pin point the exact case. // @@ -19,13 +18,11 @@ impl FormatRule for FormatTsTypeParameterList { } else { TrailingSeparator::default() }; - Ok(join_elements( - soft_line_break_or_space(), - formatter.format_separated_with_options( - node, - || token(","), + + f.join_with(&soft_line_break_or_space()) + .entries(node.format_separated(token(",")).with_options( FormatSeparatedOptions::default().with_trailing_separator(trailing_separator), - )?, - )) + )) + .finish() } } diff --git a/crates/rome_js_formatter/src/ts/lists/union_type_variant_list.rs b/crates/rome_js_formatter/src/ts/lists/union_type_variant_list.rs index ff0f4a3b956..1ffd1a0695b 100644 --- a/crates/rome_js_formatter/src/ts/lists/union_type_variant_list.rs +++ b/crates/rome_js_formatter/src/ts/lists/union_type_variant_list.rs @@ -1,48 +1,57 @@ use crate::generated::FormatTsUnionTypeVariantList; use crate::prelude::*; -use rome_js_syntax::TsUnionTypeVariantList; -use rome_rowan::AstSeparatedList; +use rome_formatter::write; +use rome_js_syntax::{JsLanguage, TsType, TsUnionTypeVariantList}; +use rome_rowan::{AstSeparatedElement, AstSeparatedList}; impl FormatRule for FormatTsUnionTypeVariantList { type Context = JsFormatContext; - fn format( - node: &TsUnionTypeVariantList, - formatter: &JsFormatter, - ) -> FormatResult { - let mut elements = Vec::with_capacity(node.len()); + fn fmt(node: &TsUnionTypeVariantList, f: &mut JsFormatter) -> FormatResult<()> { let last_index = node.len().saturating_sub(1); - for (index, item) in node.elements().enumerate() { - let ty = formatted![formatter, [item.node().format()]]?; - let separator = item.trailing_separator()?; - - let separator = match separator { - Some(token) => { - if index == last_index { - formatter.format_replaced(token, empty_element()) - } else { - formatted![ - formatter, - [soft_line_break_or_space(), token.format(), space_token()] - ]? - } + f.join() + .entries( + node.elements() + .enumerate() + .map(|(index, item)| FormatTypeVariant { + last: index == last_index, + element: item, + }), + ) + .finish() + } +} + +pub struct FormatTypeVariant { + pub last: bool, + pub element: AstSeparatedElement, +} + +impl Format for FormatTypeVariant { + fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> { + write!(f, [group_elements(&self.element.node().format())])?; + + let separator = self.element.trailing_separator()?; + + match separator { + Some(token) => { + if self.last { + write!(f, [format_replaced(token, &empty_element())])?; + } else { + write![ + f, + [soft_line_break_or_space(), token.format(), space_token()] + ]?; } - None => { - if index == last_index { - empty_element() - } else { - formatted![ - formatter, - [soft_line_break_or_space(), token("|"), space_token()] - ]? - } + } + None => { + if !self.last { + write![f, [soft_line_break_or_space(), token("|"), space_token()]]?; } - }; - - elements.push(format_elements![group_elements(ty), separator]); + } } - Ok(concat_elements(elements)) + Ok(()) } } diff --git a/crates/rome_js_formatter/src/ts/module/export_as_namespace_clause.rs b/crates/rome_js_formatter/src/ts/module/export_as_namespace_clause.rs index 1ce3cf7dbcf..3b0ecb2ac91 100644 --- a/crates/rome_js_formatter/src/ts/module/export_as_namespace_clause.rs +++ b/crates/rome_js_formatter/src/ts/module/export_as_namespace_clause.rs @@ -1,14 +1,12 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::TsExportAsNamespaceClause; use rome_js_syntax::TsExportAsNamespaceClauseFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsExportAsNamespaceClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsExportAsNamespaceClause, f: &mut JsFormatter) -> FormatResult<()> { let TsExportAsNamespaceClauseFields { as_token, namespace_token, @@ -16,19 +14,18 @@ impl FormatNodeFields for FormatNodeRule for FormatNodeRule { - fn format_fields( - node: &TsExportAssignmentClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsExportAssignmentClause, f: &mut JsFormatter) -> FormatResult<()> { let TsExportAssignmentClauseFields { eq_token, expression, semicolon_token, } = node.as_fields(); - format_with_semicolon( - formatter, - formatted![ - formatter, - [eq_token.format(), space_token(), expression.format(),] - ]?, - semicolon_token, + write!( + f, + [FormatWithSemicolon::new( + &format_args!(eq_token.format(), space_token(), expression.format()), + semicolon_token.as_ref() + )] ) } } diff --git a/crates/rome_js_formatter/src/ts/module/export_declare_clause.rs b/crates/rome_js_formatter/src/ts/module/export_declare_clause.rs index 0fbab86effa..eeb6b0ce2ee 100644 --- a/crates/rome_js_formatter/src/ts/module/export_declare_clause.rs +++ b/crates/rome_js_formatter/src/ts/module/export_declare_clause.rs @@ -1,20 +1,18 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsExportDeclareClause; use rome_js_syntax::TsExportDeclareClauseFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsExportDeclareClause, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsExportDeclareClause, f: &mut JsFormatter) -> FormatResult<()> { let TsExportDeclareClauseFields { declare_token, declaration, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [declare_token.format(), space_token(), declaration.format(),] ] } diff --git a/crates/rome_js_formatter/src/ts/module/import_type.rs b/crates/rome_js_formatter/src/ts/module/import_type.rs index a26418afd3e..4787a74f46d 100644 --- a/crates/rome_js_formatter/src/ts/module/import_type.rs +++ b/crates/rome_js_formatter/src/ts/module/import_type.rs @@ -1,11 +1,12 @@ use crate::prelude::*; use crate::utils::{FormatLiteralStringToken, StringLiteralParentKind}; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsImportType; use rome_js_syntax::TsImportTypeFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsImportType, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &TsImportType, f: &mut JsFormatter) -> FormatResult<()> { let TsImportTypeFields { typeof_token, import_token, @@ -16,12 +17,13 @@ impl FormatNodeFields for FormatNodeRule { type_arguments, } = node.as_fields(); - formatted![ - formatter, + if let Some(typeof_token) = typeof_token { + write!(f, [typeof_token.format(), space_token()])?; + } + + write![ + f, [ - typeof_token - .format() - .with_or_empty(|token| formatted![formatter, [token, space_token()]]), import_token.format(), l_paren_token.format(), FormatLiteralStringToken::new( diff --git a/crates/rome_js_formatter/src/ts/module/import_type_qualifier.rs b/crates/rome_js_formatter/src/ts/module/import_type_qualifier.rs index 74d8ba22320..6717ec91007 100644 --- a/crates/rome_js_formatter/src/ts/module/import_type_qualifier.rs +++ b/crates/rome_js_formatter/src/ts/module/import_type_qualifier.rs @@ -1,15 +1,13 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsImportTypeQualifier; use rome_js_syntax::TsImportTypeQualifierFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsImportTypeQualifier, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsImportTypeQualifier, f: &mut JsFormatter) -> FormatResult<()> { let TsImportTypeQualifierFields { dot_token, right } = node.as_fields(); - formatted![formatter, [dot_token.format(), right.format(),]] + write![f, [dot_token.format(), right.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/statements/declare_statement.rs b/crates/rome_js_formatter/src/ts/statements/declare_statement.rs index 0f3301881ed..cf58fe3964f 100644 --- a/crates/rome_js_formatter/src/ts/statements/declare_statement.rs +++ b/crates/rome_js_formatter/src/ts/statements/declare_statement.rs @@ -1,19 +1,17 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsDeclareStatement; use rome_js_syntax::TsDeclareStatementFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsDeclareStatement, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsDeclareStatement, f: &mut JsFormatter) -> FormatResult<()> { let TsDeclareStatementFields { declaration, declare_token, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [declare_token.format(), space_token(), declaration.format()] ] } diff --git a/crates/rome_js_formatter/src/ts/types/any_type.rs b/crates/rome_js_formatter/src/ts/types/any_type.rs index df62af9fc13..b638059b5c8 100644 --- a/crates/rome_js_formatter/src/ts/types/any_type.rs +++ b/crates/rome_js_formatter/src/ts/types/any_type.rs @@ -1,11 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsAnyType, TsAnyTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsAnyType, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &TsAnyType, f: &mut JsFormatter) -> FormatResult<()> { let TsAnyTypeFields { any_token } = node.as_fields(); - formatted![formatter, [any_token.format()]] + write![f, [any_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/array_type.rs b/crates/rome_js_formatter/src/ts/types/array_type.rs index a9eaa0f056a..8fa610f457a 100644 --- a/crates/rome_js_formatter/src/ts/types/array_type.rs +++ b/crates/rome_js_formatter/src/ts/types/array_type.rs @@ -1,16 +1,17 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsArrayType, TsArrayTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsArrayType, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &TsArrayType, f: &mut JsFormatter) -> FormatResult<()> { let TsArrayTypeFields { l_brack_token, element_type, r_brack_token, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ element_type.format(), l_brack_token.format(), diff --git a/crates/rome_js_formatter/src/ts/types/asserts_return_type.rs b/crates/rome_js_formatter/src/ts/types/asserts_return_type.rs index 1ec738d56e7..f5573e7dc52 100644 --- a/crates/rome_js_formatter/src/ts/types/asserts_return_type.rs +++ b/crates/rome_js_formatter/src/ts/types/asserts_return_type.rs @@ -1,20 +1,18 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsAssertsReturnType; use rome_js_syntax::TsAssertsReturnTypeFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsAssertsReturnType, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsAssertsReturnType, f: &mut JsFormatter) -> FormatResult<()> { let TsAssertsReturnTypeFields { parameter_name, asserts_token, predicate, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ asserts_token.format(), space_token(), diff --git a/crates/rome_js_formatter/src/ts/types/big_int_literal_type.rs b/crates/rome_js_formatter/src/ts/types/big_int_literal_type.rs index 089defb8f66..9e635163bb5 100644 --- a/crates/rome_js_formatter/src/ts/types/big_int_literal_type.rs +++ b/crates/rome_js_formatter/src/ts/types/big_int_literal_type.rs @@ -1,17 +1,15 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsBigIntLiteralType, TsBigIntLiteralTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsBigIntLiteralType, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsBigIntLiteralType, f: &mut JsFormatter) -> FormatResult<()> { let TsBigIntLiteralTypeFields { minus_token, literal_token, } = node.as_fields(); - formatted![formatter, [minus_token.format(), literal_token.format()]] + write![f, [minus_token.format(), literal_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/bigint_type.rs b/crates/rome_js_formatter/src/ts/types/bigint_type.rs index e9814f8b5d3..d06a9928096 100644 --- a/crates/rome_js_formatter/src/ts/types/bigint_type.rs +++ b/crates/rome_js_formatter/src/ts/types/bigint_type.rs @@ -1,11 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsBigintType, TsBigintTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsBigintType, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &TsBigintType, f: &mut JsFormatter) -> FormatResult<()> { let TsBigintTypeFields { bigint_token } = node.as_fields(); - formatted![formatter, [bigint_token.format()]] + write![f, [bigint_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/boolean_literal_type.rs b/crates/rome_js_formatter/src/ts/types/boolean_literal_type.rs index da0edc3857a..baa72660f50 100644 --- a/crates/rome_js_formatter/src/ts/types/boolean_literal_type.rs +++ b/crates/rome_js_formatter/src/ts/types/boolean_literal_type.rs @@ -1,13 +1,11 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsBooleanLiteralType, TsBooleanLiteralTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsBooleanLiteralType, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsBooleanLiteralType, f: &mut JsFormatter) -> FormatResult<()> { let TsBooleanLiteralTypeFields { literal } = node.as_fields(); - formatted![formatter, [literal.format()]] + write![f, [literal.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/boolean_type.rs b/crates/rome_js_formatter/src/ts/types/boolean_type.rs index b71a8e6100c..40508946661 100644 --- a/crates/rome_js_formatter/src/ts/types/boolean_type.rs +++ b/crates/rome_js_formatter/src/ts/types/boolean_type.rs @@ -1,11 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsBooleanType, TsBooleanTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsBooleanType, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &TsBooleanType, f: &mut JsFormatter) -> FormatResult<()> { let TsBooleanTypeFields { boolean_token } = node.as_fields(); - formatted![formatter, [boolean_token.format()]] + write![f, [boolean_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/conditional_type.rs b/crates/rome_js_formatter/src/ts/types/conditional_type.rs index 56b0857e97e..60bccdd7e9b 100644 --- a/crates/rome_js_formatter/src/ts/types/conditional_type.rs +++ b/crates/rome_js_formatter/src/ts/types/conditional_type.rs @@ -4,10 +4,7 @@ use crate::FormatNodeFields; use rome_js_syntax::TsConditionalType; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsConditionalType, - formatter: &JsFormatter, - ) -> FormatResult { - format_conditional(Conditional::Type(node.clone()), formatter, false) + fn fmt_fields(node: &TsConditionalType, formatter: &mut JsFormatter) -> FormatResult<()> { + format_conditional(&Conditional::Type(node.clone()), formatter, false) } } diff --git a/crates/rome_js_formatter/src/ts/types/constructor_type.rs b/crates/rome_js_formatter/src/ts/types/constructor_type.rs index 36018f046ae..e23fb710485 100644 --- a/crates/rome_js_formatter/src/ts/types/constructor_type.rs +++ b/crates/rome_js_formatter/src/ts/types/constructor_type.rs @@ -1,13 +1,11 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsConstructorType; use rome_js_syntax::TsConstructorTypeFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsConstructorType, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsConstructorType, f: &mut JsFormatter) -> FormatResult<()> { let TsConstructorTypeFields { abstract_token, new_token, @@ -17,12 +15,13 @@ impl FormatNodeFields for FormatNodeRule { return_type, } = node.as_fields(); - formatted![ - formatter, + if let Some(abstract_token) = abstract_token { + write!(f, [abstract_token.format(), space_token()])?; + } + + write![ + f, [ - abstract_token - .format() - .with_or_empty(|element| formatted![formatter, [element, space_token()]]), new_token.format(), type_parameters.format(), parameters.format(), diff --git a/crates/rome_js_formatter/src/ts/types/function_type.rs b/crates/rome_js_formatter/src/ts/types/function_type.rs index 9d49ba38036..ee3e35ded6e 100644 --- a/crates/rome_js_formatter/src/ts/types/function_type.rs +++ b/crates/rome_js_formatter/src/ts/types/function_type.rs @@ -1,13 +1,11 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsFunctionType; use rome_js_syntax::TsFunctionTypeFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsFunctionType, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsFunctionType, f: &mut JsFormatter) -> FormatResult<()> { let TsFunctionTypeFields { parameters, fat_arrow_token, @@ -15,8 +13,8 @@ impl FormatNodeFields for FormatNodeRule { return_type, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ type_parameters.format(), parameters.format(), diff --git a/crates/rome_js_formatter/src/ts/types/indexed_access_type.rs b/crates/rome_js_formatter/src/ts/types/indexed_access_type.rs index 59a11ba3518..4e2df57f08a 100644 --- a/crates/rome_js_formatter/src/ts/types/indexed_access_type.rs +++ b/crates/rome_js_formatter/src/ts/types/indexed_access_type.rs @@ -1,21 +1,19 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsIndexedAccessType; use rome_js_syntax::TsIndexedAccessTypeFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsIndexedAccessType, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsIndexedAccessType, f: &mut JsFormatter) -> FormatResult<()> { let TsIndexedAccessTypeFields { object_type, l_brack_token, index_type, r_brack_token, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ object_type.format(), l_brack_token.format(), diff --git a/crates/rome_js_formatter/src/ts/types/infer_type.rs b/crates/rome_js_formatter/src/ts/types/infer_type.rs index 9baec0bd2ee..6531b6f1936 100644 --- a/crates/rome_js_formatter/src/ts/types/infer_type.rs +++ b/crates/rome_js_formatter/src/ts/types/infer_type.rs @@ -1,15 +1,17 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsInferType, TsInferTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsInferType, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &TsInferType, f: &mut JsFormatter) -> FormatResult<()> { let TsInferTypeFields { infer_token, type_parameter, } = node.as_fields(); - let infer = infer_token.format(); - let type_parameter = type_parameter.format(); - formatted![formatter, [infer, space_token(), type_parameter]] + write![ + f, + [infer_token.format(), space_token(), type_parameter.format()] + ] } } diff --git a/crates/rome_js_formatter/src/ts/types/intersection_type.rs b/crates/rome_js_formatter/src/ts/types/intersection_type.rs index e076ac8e912..e312e698cf1 100644 --- a/crates/rome_js_formatter/src/ts/types/intersection_type.rs +++ b/crates/rome_js_formatter/src/ts/types/intersection_type.rs @@ -1,35 +1,59 @@ use crate::prelude::*; use crate::FormatNodeFields; -use rome_js_syntax::TsIntersectionType; +use rome_formatter::{format_args, write}; use rome_js_syntax::TsIntersectionTypeFields; +use rome_js_syntax::{JsSyntaxToken, TsIntersectionType}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsIntersectionType, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsIntersectionType, f: &mut JsFormatter) -> FormatResult<()> { let TsIntersectionTypeFields { leading_separator_token, types, } = node.as_fields(); - let leading_separator_token = match leading_separator_token { + write!( + f, + [group_elements(&indent(&format_args!( + soft_line_break(), + FormatTypeSetLeadingSeparator { + separator: "&", + leading_separator: leading_separator_token.as_ref() + }, + types.format() + )))] + ) + } +} + +pub(crate) struct FormatTypeSetLeadingSeparator<'a> { + pub(crate) separator: &'static str, + pub(crate) leading_separator: Option<&'a JsSyntaxToken>, +} + +impl Format for FormatTypeSetLeadingSeparator<'_> { + fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> { + match &self.leading_separator { Some(token) => { // The SyntaxToken is converted into a FormatElement using // Token::from to strip the token's trivia pieces which are // then reinserted in format_replaced outside of the // if_group_breaks block to avoid removing comments when the // group does not break - let replaced = - if_group_breaks(format_elements![Token::from(&token), space_token()]); - formatter.format_replaced(&token, replaced) + write!( + f, + [format_replaced( + token, + &if_group_breaks(&format_args!(format_trimmed_token(token), space_token())) + )] + ) } - None => if_group_breaks(format_elements![token("&"), space_token()]), - }; - - Ok(group_elements(indent(formatted![ - formatter, - [soft_line_break(), leading_separator_token, types.format(),] - ]?))) + None => write!( + f, + [if_group_breaks(&format_args![ + token(self.separator), + space_token() + ])] + ), + } } } diff --git a/crates/rome_js_formatter/src/ts/types/mapped_type.rs b/crates/rome_js_formatter/src/ts/types/mapped_type.rs index 5be5baa2010..cdfeb7287a6 100644 --- a/crates/rome_js_formatter/src/ts/types/mapped_type.rs +++ b/crates/rome_js_formatter/src/ts/types/mapped_type.rs @@ -1,10 +1,11 @@ use crate::prelude::*; -use crate::utils::format_with_semicolon; +use crate::utils::FormatWithSemicolon; use crate::FormatNodeFields; +use rome_formatter::{format_args, write}; use rome_js_syntax::{TsMappedType, TsMappedTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsMappedType, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &TsMappedType, f: &mut JsFormatter) -> FormatResult<()> { let TsMappedTypeFields { l_curly_token, readonly_modifier, @@ -20,40 +21,33 @@ impl FormatNodeFields for FormatNodeRule { r_curly_token, } = node.as_fields(); - formatter - .delimited( + write!( + f, + [format_delimited( &l_curly_token?, - format_with_semicolon( - formatter, - formatted![ - formatter, - [ - readonly_modifier - .format() - .with_or_empty(|readonly| formatted![ - formatter, - [readonly, space_token()] - ]), - l_brack_token.format(), - property_name.format(), - space_token(), - in_token.format(), - space_token(), - keys_type.format(), - as_clause.format().with_or_empty(|clause| formatted![ - formatter, - [space_token(), clause] - ]), - r_brack_token.format(), - optional_modifier.format(), - mapped_type.format(), - ] - ]?, - semicolon_token, - )?, + &FormatWithSemicolon::new( + &format_args!( + readonly_modifier + .format() + .with_or_empty(|readonly, f| write![f, [readonly, space_token()]]), + l_brack_token.format(), + property_name.format(), + space_token(), + in_token.format(), + space_token(), + keys_type.format(), + as_clause + .format() + .with_or_empty(|clause, f| write![f, [space_token(), clause]]), + r_brack_token.format(), + optional_modifier.format(), + mapped_type.format(), + ), + semicolon_token.as_ref(), + ), &r_curly_token?, ) - .block_indent() - .finish() + .block_indent()] + ) } } diff --git a/crates/rome_js_formatter/src/ts/types/never_type.rs b/crates/rome_js_formatter/src/ts/types/never_type.rs index 1502d7e75fe..d0375107fd5 100644 --- a/crates/rome_js_formatter/src/ts/types/never_type.rs +++ b/crates/rome_js_formatter/src/ts/types/never_type.rs @@ -1,10 +1,11 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsNeverType, TsNeverTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsNeverType, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &TsNeverType, f: &mut JsFormatter) -> FormatResult<()> { let TsNeverTypeFields { never_token } = node.as_fields(); - formatted![formatter, [never_token.format()]] + write![f, [never_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/non_primitive_type.rs b/crates/rome_js_formatter/src/ts/types/non_primitive_type.rs index 6888d623504..a55491e81cb 100644 --- a/crates/rome_js_formatter/src/ts/types/non_primitive_type.rs +++ b/crates/rome_js_formatter/src/ts/types/non_primitive_type.rs @@ -1,14 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsNonPrimitiveType, TsNonPrimitiveTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsNonPrimitiveType, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsNonPrimitiveType, f: &mut JsFormatter) -> FormatResult<()> { let TsNonPrimitiveTypeFields { object_token } = node.as_fields(); - formatted![formatter, [object_token.format()]] + write![f, [object_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/null_literal_type.rs b/crates/rome_js_formatter/src/ts/types/null_literal_type.rs index 2528f2e50af..a79b509d534 100644 --- a/crates/rome_js_formatter/src/ts/types/null_literal_type.rs +++ b/crates/rome_js_formatter/src/ts/types/null_literal_type.rs @@ -1,13 +1,11 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsNullLiteralType, TsNullLiteralTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsNullLiteralType, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsNullLiteralType, f: &mut JsFormatter) -> FormatResult<()> { let TsNullLiteralTypeFields { literal_token } = node.as_fields(); - formatted![formatter, [literal_token.format()]] + write![f, [literal_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/number_literal_type.rs b/crates/rome_js_formatter/src/ts/types/number_literal_type.rs index 8c83046c20d..a1e3e467774 100644 --- a/crates/rome_js_formatter/src/ts/types/number_literal_type.rs +++ b/crates/rome_js_formatter/src/ts/types/number_literal_type.rs @@ -1,16 +1,14 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsNumberLiteralType, TsNumberLiteralTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsNumberLiteralType, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsNumberLiteralType, f: &mut JsFormatter) -> FormatResult<()> { let TsNumberLiteralTypeFields { minus_token, literal_token, } = node.as_fields(); - formatted![formatter, [minus_token.format(), literal_token.format()]] + write![f, [minus_token.format(), literal_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/number_type.rs b/crates/rome_js_formatter/src/ts/types/number_type.rs index 72808591d63..df80f5ea6e8 100644 --- a/crates/rome_js_formatter/src/ts/types/number_type.rs +++ b/crates/rome_js_formatter/src/ts/types/number_type.rs @@ -1,11 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsNumberType, TsNumberTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsNumberType, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &TsNumberType, f: &mut JsFormatter) -> FormatResult<()> { let TsNumberTypeFields { number_token } = node.as_fields(); - formatted![formatter, [number_token.format()]] + write![f, [number_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/object_type.rs b/crates/rome_js_formatter/src/ts/types/object_type.rs index 71478c28041..c7a09f8c8e1 100644 --- a/crates/rome_js_formatter/src/ts/types/object_type.rs +++ b/crates/rome_js_formatter/src/ts/types/object_type.rs @@ -1,10 +1,11 @@ use crate::prelude::*; use crate::utils::has_leading_newline; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsObjectType, TsObjectTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsObjectType, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &TsObjectType, f: &mut JsFormatter) -> FormatResult<()> { let TsObjectTypeFields { l_curly_token, members, @@ -12,23 +13,21 @@ impl FormatNodeFields for FormatNodeRule { } = node.as_fields(); if has_leading_newline(members.syntax()) { - formatter - .delimited( - &l_curly_token?, - formatted![formatter, [members.format()]]?, - &r_curly_token?, - ) - .block_indent() - .finish() + write!( + f, + [ + format_delimited(&l_curly_token?, &members.format(), &r_curly_token?) + .block_indent() + ] + ) } else { - formatter - .delimited( - &l_curly_token?, - formatted![formatter, [members.format()]]?, - &r_curly_token?, - ) - .soft_block_spaces() - .finish() + write!( + f, + [ + format_delimited(&l_curly_token?, &members.format(), &r_curly_token?,) + .soft_block_spaces() + ] + ) } } } diff --git a/crates/rome_js_formatter/src/ts/types/parenthesized_type.rs b/crates/rome_js_formatter/src/ts/types/parenthesized_type.rs index 62a10f36c65..37072a24b3e 100644 --- a/crates/rome_js_formatter/src/ts/types/parenthesized_type.rs +++ b/crates/rome_js_formatter/src/ts/types/parenthesized_type.rs @@ -1,26 +1,23 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsParenthesizedType; use rome_js_syntax::TsParenthesizedTypeFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsParenthesizedType, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsParenthesizedType, f: &mut JsFormatter) -> FormatResult<()> { let TsParenthesizedTypeFields { l_paren_token, ty, r_paren_token, } = node.as_fields(); - formatter - .delimited( - &l_paren_token?, - formatted![formatter, [ty.format()]]?, - &r_paren_token?, - ) - .soft_block_indent() - .finish() + write!( + f, + [ + format_delimited(&l_paren_token?, &ty.format(), &r_paren_token?,) + .soft_block_indent() + ] + ) } } diff --git a/crates/rome_js_formatter/src/ts/types/predicate_return_type.rs b/crates/rome_js_formatter/src/ts/types/predicate_return_type.rs index 11501ff6d18..95c666ee90b 100644 --- a/crates/rome_js_formatter/src/ts/types/predicate_return_type.rs +++ b/crates/rome_js_formatter/src/ts/types/predicate_return_type.rs @@ -1,20 +1,18 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::TsPredicateReturnType; use rome_js_syntax::TsPredicateReturnTypeFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsPredicateReturnType, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsPredicateReturnType, f: &mut JsFormatter) -> FormatResult<()> { let TsPredicateReturnTypeFields { parameter_name, is_token, ty, } = node.as_fields(); - formatted![ - formatter, + write![ + f, [ parameter_name.format(), space_token(), diff --git a/crates/rome_js_formatter/src/ts/types/reference_type.rs b/crates/rome_js_formatter/src/ts/types/reference_type.rs index c784dd3618a..12564fd6ba4 100644 --- a/crates/rome_js_formatter/src/ts/types/reference_type.rs +++ b/crates/rome_js_formatter/src/ts/types/reference_type.rs @@ -1,17 +1,15 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsReferenceType, TsReferenceTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsReferenceType, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsReferenceType, f: &mut JsFormatter) -> FormatResult<()> { let TsReferenceTypeFields { name, type_arguments, } = node.as_fields(); - formatted![formatter, [name.format(), type_arguments.format()]] + write![f, [name.format(), type_arguments.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/string_literal_type.rs b/crates/rome_js_formatter/src/ts/types/string_literal_type.rs index 5b2de4021ae..25c1f2deecf 100644 --- a/crates/rome_js_formatter/src/ts/types/string_literal_type.rs +++ b/crates/rome_js_formatter/src/ts/types/string_literal_type.rs @@ -1,21 +1,19 @@ use crate::prelude::*; use crate::utils::{FormatLiteralStringToken, StringLiteralParentKind}; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsStringLiteralType, TsStringLiteralTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsStringLiteralType, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsStringLiteralType, f: &mut JsFormatter) -> FormatResult<()> { let TsStringLiteralTypeFields { literal_token } = node.as_fields(); - formatted![ - formatter, + write!( + f, [FormatLiteralStringToken::new( &literal_token?, StringLiteralParentKind::Expression )] - ] + ) } } diff --git a/crates/rome_js_formatter/src/ts/types/string_type.rs b/crates/rome_js_formatter/src/ts/types/string_type.rs index ed6a36f3ef8..9e4517c40d3 100644 --- a/crates/rome_js_formatter/src/ts/types/string_type.rs +++ b/crates/rome_js_formatter/src/ts/types/string_type.rs @@ -1,11 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsStringType, TsStringTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsStringType, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &TsStringType, f: &mut JsFormatter) -> FormatResult<()> { let TsStringTypeFields { string_token } = node.as_fields(); - formatted![formatter, [string_token.format()]] + write![f, [string_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/symbol_type.rs b/crates/rome_js_formatter/src/ts/types/symbol_type.rs index 043abbb8edf..bef030019b0 100644 --- a/crates/rome_js_formatter/src/ts/types/symbol_type.rs +++ b/crates/rome_js_formatter/src/ts/types/symbol_type.rs @@ -1,11 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsSymbolType, TsSymbolTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsSymbolType, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &TsSymbolType, f: &mut JsFormatter) -> FormatResult<()> { let TsSymbolTypeFields { symbol_token } = node.as_fields(); - formatted![formatter, [symbol_token.format()]] + write![f, [symbol_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/this_type.rs b/crates/rome_js_formatter/src/ts/types/this_type.rs index d14490e810c..4e2973a25df 100644 --- a/crates/rome_js_formatter/src/ts/types/this_type.rs +++ b/crates/rome_js_formatter/src/ts/types/this_type.rs @@ -1,11 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsThisType, TsThisTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsThisType, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &TsThisType, f: &mut JsFormatter) -> FormatResult<()> { let TsThisTypeFields { this_token } = node.as_fields(); - formatted![formatter, [this_token.format()]] + write![f, [this_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/tuple_type.rs b/crates/rome_js_formatter/src/ts/types/tuple_type.rs index 87b66088313..204dc722925 100644 --- a/crates/rome_js_formatter/src/ts/types/tuple_type.rs +++ b/crates/rome_js_formatter/src/ts/types/tuple_type.rs @@ -1,22 +1,22 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsTupleType, TsTupleTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsTupleType, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &TsTupleType, f: &mut JsFormatter) -> FormatResult<()> { let TsTupleTypeFields { l_brack_token, elements, r_brack_token, } = node.as_fields(); - formatter - .delimited( - &l_brack_token?, - formatted![formatter, [elements.format()]]?, - &r_brack_token?, - ) - .soft_block_indent() - .finish() + write!( + f, + [ + format_delimited(&l_brack_token?, &elements.format(), &r_brack_token?,) + .soft_block_indent() + ] + ) } } diff --git a/crates/rome_js_formatter/src/ts/types/type_operator_type.rs b/crates/rome_js_formatter/src/ts/types/type_operator_type.rs index f4630774919..4253d1c72d7 100644 --- a/crates/rome_js_formatter/src/ts/types/type_operator_type.rs +++ b/crates/rome_js_formatter/src/ts/types/type_operator_type.rs @@ -1,22 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsTypeOperatorType, TsTypeOperatorTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsTypeOperatorType, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsTypeOperatorType, f: &mut JsFormatter) -> FormatResult<()> { let TsTypeOperatorTypeFields { operator_token, ty } = node.as_fields(); - formatted![ - formatter, - [ - operator_token - .format() - .with(|operator| { formatted![formatter, [operator, space_token()]] }), - ty.format() - ] - ] + write![f, [operator_token.format(), space_token(), ty.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/typeof_type.rs b/crates/rome_js_formatter/src/ts/types/typeof_type.rs index 9f8dc5064d8..dfb18c2928c 100644 --- a/crates/rome_js_formatter/src/ts/types/typeof_type.rs +++ b/crates/rome_js_formatter/src/ts/types/typeof_type.rs @@ -1,16 +1,22 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsTypeofType, TsTypeofTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsTypeofType, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &TsTypeofType, f: &mut JsFormatter) -> FormatResult<()> { let TsTypeofTypeFields { typeof_token, expression_name, } = node.as_fields(); - let r#typeof = typeof_token.format(); - let expression_name = expression_name.format(); - formatted![formatter, [r#typeof, space_token(), expression_name]] + write![ + f, + [ + typeof_token.format(), + space_token(), + expression_name.format() + ] + ] } } diff --git a/crates/rome_js_formatter/src/ts/types/undefined_type.rs b/crates/rome_js_formatter/src/ts/types/undefined_type.rs index f4ef90134c9..2bad1a8a9c2 100644 --- a/crates/rome_js_formatter/src/ts/types/undefined_type.rs +++ b/crates/rome_js_formatter/src/ts/types/undefined_type.rs @@ -1,14 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsUndefinedType, TsUndefinedTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields( - node: &TsUndefinedType, - formatter: &JsFormatter, - ) -> FormatResult { + fn fmt_fields(node: &TsUndefinedType, f: &mut JsFormatter) -> FormatResult<()> { let TsUndefinedTypeFields { undefined_token } = node.as_fields(); - formatted![formatter, [undefined_token.format()]] + write![f, [undefined_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/union_type.rs b/crates/rome_js_formatter/src/ts/types/union_type.rs index 7d8b169b10e..3646b98a683 100644 --- a/crates/rome_js_formatter/src/ts/types/union_type.rs +++ b/crates/rome_js_formatter/src/ts/types/union_type.rs @@ -1,48 +1,46 @@ use crate::prelude::*; +use crate::ts::types::intersection_type::FormatTypeSetLeadingSeparator; use crate::FormatNodeFields; +use rome_formatter::{format_args, write, Buffer, VecBuffer}; use rome_js_syntax::TsUnionType; use rome_js_syntax::TsUnionTypeFields; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsUnionType, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &TsUnionType, f: &mut JsFormatter) -> FormatResult<()> { let TsUnionTypeFields { leading_separator_token, types, } = node.as_fields(); - let leading_separator_token = match leading_separator_token { - Some(token) => { - // The SyntaxToken is converted into a FormatElement using - // Token::from to strip the token's trivia pieces which are - // then reinserted informat_replaced outside of the - // if_group_breaks block to avoid removing comments when the - // group does not break - let replaced = - if_group_breaks(format_elements![Token::from(&token), space_token()]); - formatter.format_replaced(&token, replaced) - } - None => if_group_breaks(format_elements![token("|"), space_token()]), - }; + let mut buffer = VecBuffer::new(f.state_mut()); + write!( + buffer, + [ + FormatTypeSetLeadingSeparator { + separator: "|", + leading_separator: leading_separator_token.as_ref() + }, + types.format() + ] + )?; - let types = formatted![formatter, [types.format()]]?; + let types = buffer.into_element(); // Push trailing comments for the union out of the group (and indent block), // so any potential line break doesn't influence the formatting of the type itself let (leading_comments, types, trailing_comments) = types.split_trivia(); - formatted![ - formatter, + write![ + f, [ - group_elements(indent(formatted![ - formatter, - [ - soft_line_break(), - leading_separator_token, - leading_comments, - types, - ] - ]?)), - trailing_comments + group_elements(&indent(&format_args![ + soft_line_break(), + format_once(|f| { + f.write_element(leading_comments)?; + f.write_element(types) + }) + ])), + format_once(|f| { f.write_element(trailing_comments) }) ] ] } diff --git a/crates/rome_js_formatter/src/ts/types/unknown_type.rs b/crates/rome_js_formatter/src/ts/types/unknown_type.rs index cd1a041f266..a07c0051513 100644 --- a/crates/rome_js_formatter/src/ts/types/unknown_type.rs +++ b/crates/rome_js_formatter/src/ts/types/unknown_type.rs @@ -1,10 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsUnknownType, TsUnknownTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsUnknownType, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &TsUnknownType, f: &mut JsFormatter) -> FormatResult<()> { let TsUnknownTypeFields { unknown_token } = node.as_fields(); - formatted![formatter, [unknown_token.format()]] + + write![f, [unknown_token.format()]] } } diff --git a/crates/rome_js_formatter/src/ts/types/void_type.rs b/crates/rome_js_formatter/src/ts/types/void_type.rs index 91b7a946e00..2297a999d26 100644 --- a/crates/rome_js_formatter/src/ts/types/void_type.rs +++ b/crates/rome_js_formatter/src/ts/types/void_type.rs @@ -1,11 +1,12 @@ use crate::prelude::*; use crate::FormatNodeFields; +use rome_formatter::write; use rome_js_syntax::{TsVoidType, TsVoidTypeFields}; impl FormatNodeFields for FormatNodeRule { - fn format_fields(node: &TsVoidType, formatter: &JsFormatter) -> FormatResult { + fn fmt_fields(node: &TsVoidType, f: &mut JsFormatter) -> FormatResult<()> { let TsVoidTypeFields { void_token } = node.as_fields(); - formatted![formatter, [void_token.format()]] + write![f, [void_token.format()]] } } diff --git a/crates/rome_js_formatter/src/utils/array.rs b/crates/rome_js_formatter/src/utils/array.rs index aea61101c22..3bad82e4989 100644 --- a/crates/rome_js_formatter/src/utils/array.rs +++ b/crates/rome_js_formatter/src/utils/array.rs @@ -1,6 +1,7 @@ use crate::prelude::*; - use crate::AsFormat; + +use rome_formatter::write; use rome_js_syntax::{ JsAnyArrayAssignmentPatternElement, JsAnyArrayBindingPatternElement, JsAnyArrayElement, JsLanguage, @@ -8,10 +9,7 @@ use rome_js_syntax::{ use rome_rowan::{AstNode, AstSeparatedList}; /// Utility function to print array-like nodes (array expressions, array bindings and assignment patterns) -pub(crate) fn format_array_node( - node: &N, - formatter: &JsFormatter, -) -> FormatResult +pub(crate) fn write_array_node(node: &N, f: &mut JsFormatter) -> FormatResult<()> where N: AstSeparatedList, for<'a> I: ArrayNodeElement + AsFormat<'a>, @@ -19,48 +17,48 @@ where // Specifically do not use format_separated as arrays need separators // inserted after holes regardless of the formatting since this makes a // semantic difference + + let mut join = f.join_nodes_with_soft_line(); let last_index = node.len().saturating_sub(1); - let results = node - .elements() - .enumerate() - .map(|(index, element)| { - let node = element.node()?; - let separator_mode = node.separator_mode(); - let is_disallow = matches!(separator_mode, TrailingSeparatorMode::Disallow); - let is_force = matches!(separator_mode, TrailingSeparatorMode::Force); + for (index, element) in node.elements().enumerate() { + let node = element.node()?; + let separator_mode = node.separator_mode(); - let formatted_element = formatted![formatter, [node.format()]]?; - let separator = if is_disallow { - // Trailing separators are disallowed, replace it with an empty element - if let Some(separator) = element.trailing_separator()? { - formatter.format_replaced(separator, empty_element()) + let is_disallow = matches!(separator_mode, TrailingSeparatorMode::Disallow); + let is_force = matches!(separator_mode, TrailingSeparatorMode::Force); + + join.entry( + node.syntax(), + &format_with(|f| { + write!(f, [group_elements(&node.format())])?; + + if is_disallow { + // Trailing separators are disallowed, replace it with an empty element + if let Some(separator) = element.trailing_separator()? { + write!(f, [format_replaced(separator, &empty_element())])?; + } + } else if is_force || index != last_index { + // In forced separator mode or if this element is not the last in the list, print the separator + match element.trailing_separator()? { + Some(trailing) => write!(f, [trailing.format()])?, + None => write!(f, [token(",")])?, + }; + } else if let Some(separator) = element.trailing_separator()? { + write!( + f, + [format_replaced(separator, &if_group_breaks(&token(",")))] + )?; } else { - empty_element() - } - } else if is_force || index != last_index { - // In forced separator mode or if this element is not the last in the list, print the separator - formatted![ - formatter, - [&element - .trailing_separator() - .format() - .or_format(|| token(","))] - ]? - } else if let Some(separator) = element.trailing_separator()? { - formatter.format_replaced(separator, if_group_breaks(token(","))) - } else { - if_group_breaks(token(",")) - }; + write!(f, [if_group_breaks(&token(","))])?; + }; - Ok(( - node.syntax().clone(), - format_elements![group_elements(formatted_element), separator], - )) - }) - .collect::>>()?; + Ok(()) + }), + ); + } - Ok(join_elements_soft_line(results)) + join.finish() } /// Determines if a trailing separator should be inserted after an array element diff --git a/crates/rome_js_formatter/src/utils/binary_like_expression.rs b/crates/rome_js_formatter/src/utils/binary_like_expression.rs index de7b1e4f94f..2f035ede93b 100644 --- a/crates/rome_js_formatter/src/utils/binary_like_expression.rs +++ b/crates/rome_js_formatter/src/utils/binary_like_expression.rs @@ -1,10 +1,12 @@ use crate::prelude::*; +use rome_formatter::{format_args, write, Buffer, VecBuffer}; use rome_js_syntax::{ JsAnyExpression, JsAnyInProperty, JsBinaryExpression, JsBinaryOperator, JsInExpression, JsInstanceofExpression, JsLanguage, JsLogicalExpression, JsLogicalOperator, JsPrivateName, JsSyntaxKind, JsSyntaxKind::*, JsSyntaxNode, JsSyntaxToken, }; + use rome_rowan::{AstNode, SyntaxResult}; use std::cmp::Ordering; use std::fmt::Debug; @@ -95,8 +97,8 @@ use std::iter::FusedIterator; /// which is what we wanted since the beginning! pub(crate) fn format_binary_like_expression( expression: JsAnyBinaryLikeExpression, - formatter: &JsFormatter, -) -> FormatResult { + f: &mut JsFormatter, +) -> FormatResult<()> { let mut flatten_items = FlattenItems::default(); let current_node = expression.syntax().clone(); @@ -110,7 +112,7 @@ pub(crate) fn format_binary_like_expression( flatten_items.format_binary_expression_right_hand_side( left, Some(parent_operator), - formatter, + f, )?; } else { // Leaf binary like expression. Format the left hand side. @@ -119,10 +121,12 @@ pub(crate) fn format_binary_like_expression( let left = parent.left()?; let has_comments = left.syntax().has_comments_direct(); - let formatted = formatted![formatter, [left]]?; + + let mut buffer = VecBuffer::new(f.state_mut()); + write!(buffer, [left])?; flatten_items.items.push(FlattenItem::regular( - formatted, + buffer.into_element(), Some(parent_operator), has_comments.into(), )); @@ -133,10 +137,11 @@ pub(crate) fn format_binary_like_expression( // Format the top most binary like expression if let Some(root) = left { - flatten_items.format_binary_expression_right_hand_side(root, None, formatter)?; + flatten_items.format_binary_expression_right_hand_side(root, None, f)?; } - flatten_items.take_format_element(¤t_node, formatter) + let element = flatten_items.take_format_element(¤t_node, f)?; + f.write_element(element) } /// Small wrapper to identify the operation of an expression and deduce their precedence @@ -169,7 +174,7 @@ fn format_with_or_without_parenthesis( parent_operator: BinaryLikeOperator, node: &JsSyntaxNode, formatted_node: FormatElement, - formatter: &JsFormatter, + f: &mut JsFormatter, ) -> FormatResult<(FormatElement, bool)> { let compare_to = match JsAnyExpression::cast(node.clone()) { Some(JsAnyExpression::JsLogicalExpression(logical)) => { @@ -206,22 +211,22 @@ fn format_with_or_without_parenthesis( let result = if operation_is_higher { let (leading, content, trailing) = formatted_node.split_trivia(); - let formatted = formatted![ - formatter, - [ - leading, - group_elements(formatted![ - formatter, - [ - token("("), - soft_block_indent(formatted![formatter, [content, trailing]]?), - token(")") - ] - ]?) - ] + let mut buffer = VecBuffer::new(f.state_mut()); + + buffer.write_element(leading)?; + write![ + buffer, + [group_elements(&format_args![ + token("("), + soft_block_indent(&format_once(|f| { + f.write_element(content)?; + f.write_element(trailing) + })), + token(")") + ])] ]?; - (formatted, true) + (buffer.into_element(), true) } else { (formatted_node, false) }; @@ -297,14 +302,14 @@ impl FlattenItems { &mut self, expression: JsAnyBinaryLikeExpression, parent_operator: Option, - formatter: &JsFormatter, + f: &mut JsFormatter, ) -> FormatResult<()> { let should_flatten = expression.can_flatten()?; if should_flatten { - self.flatten_right_hand_side(expression, parent_operator, formatter) + self.flatten_right_hand_side(expression, parent_operator, f) } else { - self.format_new_binary_like_group(expression, parent_operator, formatter) + self.format_new_binary_like_group(expression, parent_operator, f) } } @@ -313,17 +318,20 @@ impl FlattenItems { &mut self, binary_like_expression: JsAnyBinaryLikeExpression, parent_operator: Option, - formatter: &JsFormatter, + f: &mut JsFormatter, ) -> FormatResult<()> { let right = binary_like_expression.right()?; let has_comments = right.syntax().has_comments_direct(); - let right_formatted = formatted![formatter, [right.format()]]?; + + let mut buffer = VecBuffer::new(f.state_mut()); + write!(buffer, [right.format()])?; + let right_formatted = buffer.into_element(); let (formatted_node, _) = format_with_or_without_parenthesis( binary_like_expression.operator()?, right.syntax(), right_formatted, - formatter, + f, )?; let flatten_item = @@ -340,7 +348,7 @@ impl FlattenItems { &mut self, binary_like_expression: JsAnyBinaryLikeExpression, parent_operator: Option, - formatter: &JsFormatter, + f: &mut JsFormatter, ) -> FormatResult<()> { if let Some(last) = self.items.last_mut() { // Remove any line breaks and the trailing operator so that the operator/trailing aren't part @@ -353,9 +361,9 @@ impl FlattenItems { let operator = binary_like_expression.operator()?; let operator_token = binary_like_expression.operator_token()?; - let left_formatted = self.take_format_element(left.syntax(), formatter)?; + let left_formatted = self.take_format_element(left.syntax(), f)?; let (left_formatted, _) = - format_with_or_without_parenthesis(operator, left.syntax(), left_formatted, formatter)?; + format_with_or_without_parenthesis(operator, left.syntax(), left_formatted, f)?; let operator_has_trailing_comments = operator_token.has_trailing_comments(); let mut left_item = FlattenItem::regular( @@ -372,13 +380,13 @@ impl FlattenItems { let right = binary_like_expression.right()?; + let mut buffer = VecBuffer::new(f.state_mut()); + write!(buffer, [right.format()])?; + let formatted_node = buffer.into_element(); + // Format the right node - let (formatted_right, parenthesized) = format_with_or_without_parenthesis( - operator, - right.syntax(), - formatted![formatter, [right.format()]]?, - formatter, - )?; + let (formatted_right, parenthesized) = + format_with_or_without_parenthesis(operator, right.syntax(), formatted_node, f)?; let parent_operator_has_comments = parent_operator .as_ref() @@ -415,64 +423,86 @@ impl FlattenItems { fn take_format_element( &mut self, current_node: &JsSyntaxNode, - formatter: &JsFormatter, + f: &mut JsFormatter, ) -> FormatResult { - let can_hard_group = can_hard_group(&self.items); - let len = self.items.len(); - - let mut groups = self - .items - .drain(..) - .enumerate() - // groups not like ["something &&", "something &&" ] - // we want to add a space between them in case they don't break - .map(|(index, element)| { - let operator = match &element.operator { - Some(operator) => { - // SAFETY: `syntax_token.format` never returns MissingToken. - formatted![formatter, [space_token(), operator.format()]].unwrap() - } - None => empty_element(), - }; - - let terminator = match &element.terminator { - // the last element doesn't need a space - TrailingTerminator::None if index + 1 == len => empty_element(), - TrailingTerminator::None => empty_element(), - TrailingTerminator::HardLineBreak => hard_line_break(), - }; - - format_elements![element.formatted, operator, terminator] - }); - - if can_hard_group { - // we bail early if group doesn't need to be broken. We don't need to do further checks - return Ok(join_elements(space_token(), groups)); - } - - let formatted = if is_inside_parenthesis(current_node) { - join_elements(soft_line_break_or_space(), groups) - } else if should_not_indent_if_parent_indents(current_node) { - group_elements(join_elements(soft_line_break_or_space(), groups)) - } else if should_indent_if_parent_inlines(current_node) { - // in order to correctly break, we need to check if the parent created a group - // that breaks or not. In order to do that , we need to create two conditional groups - // that behave differently depending on the situation - soft_line_indent_or_space(group_elements(join_elements( - soft_line_break_or_space(), - groups, - ))) - } else { - // if none of the previous conditions is met, - // we take take out the first element from the rest of group, then we hard group the "head" - // and we indent the rest of the groups in a new line - let head = groups.next().unwrap(); - let rest = join_elements(soft_line_break_or_space(), groups); - - format_elements![head, group_elements(soft_line_indent_or_space(rest))] - }; + let mut buffer = VecBuffer::new(f.state_mut()); + + write!( + buffer, + [format_once(|f| { + let can_hard_group = can_hard_group(&self.items); + + let mut groups = self.items.drain(..).map(|group| { + format_once(move |f| { + // groups not like ["something &&", "something &&" ] + // we want to add a space between them in case they don't break + + f.write_element(group.formatted)?; + + if let Some(operator) = group.operator { + write!(f, [space_token(), operator.format()])?; + } + + match group.terminator { + TrailingTerminator::None => (), + TrailingTerminator::HardLineBreak => write!(f, [hard_line_break()])?, + }; + + Ok(()) + }) + }); + + if can_hard_group { + // we bail early if group doesn't need to be broken. We don't need to do further checks + f.join_with(&space_token()).entries(groups).finish() + } else if is_inside_parenthesis(current_node) { + f.join_with(&soft_line_break_or_space()) + .entries(groups) + .finish() + } else if should_not_indent_if_parent_indents(current_node) { + write!( + f, + [group_elements(&format_once(|f| { + f.join_with(&soft_line_break_or_space()) + .entries(groups) + .finish() + }))] + ) + } else if should_indent_if_parent_inlines(current_node) { + // in order to correctly break, we need to check if the parent created a group + // that breaks or not. In order to do that , we need to create two conditional groups + // that behave differently depending on the situation + write!( + f, + [soft_line_indent_or_space(&group_elements(&format_once( + |f| { + f.join_with(&soft_line_break_or_space()) + .entries(groups) + .finish() + } + )))] + ) + } else { + // if none of the previous conditions is met, + // we take take out the first element from the rest of group, then we hard group the "head" + // and we indent the rest of the groups in a new line + write!(f, [groups.next().unwrap()])?; + + write!( + f, + [group_elements(&soft_line_indent_or_space(&format_once( + |f| { + f.join_with(&soft_line_break_or_space()) + .entries(groups) + .finish() + } + )))] + ) + } + })] + )?; - Ok(formatted) + Ok(buffer.into_element()) } } @@ -866,16 +896,14 @@ impl AstNode for JsAnyBinaryLikeLeftExpression { } } -impl Format for JsAnyBinaryLikeLeftExpression { - type Context = JsFormatContext; - - fn format(&self, formatter: &JsFormatter) -> FormatResult { +impl Format for JsAnyBinaryLikeLeftExpression { + fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> { match self { JsAnyBinaryLikeLeftExpression::JsAnyExpression(expression) => { - formatted![formatter, [expression.format()]] + write![f, [expression.format()]] } JsAnyBinaryLikeLeftExpression::JsPrivateName(private_name) => { - formatted![formatter, [private_name.format()]] + write![f, [private_name.format()]] } } } diff --git a/crates/rome_js_formatter/src/utils/format_conditional.rs b/crates/rome_js_formatter/src/utils/format_conditional.rs index 15367b454b3..d4d60042303 100644 --- a/crates/rome_js_formatter/src/utils/format_conditional.rs +++ b/crates/rome_js_formatter/src/utils/format_conditional.rs @@ -1,4 +1,5 @@ use crate::prelude::*; +use rome_formatter::{format_args, write}; use rome_js_syntax::{JsAnyExpression, JsConditionalExpression, TsConditionalType, TsType}; use rome_rowan::AstNode; @@ -27,32 +28,13 @@ impl Conditional { } } - fn into_format_element( - self, - formatter: &JsFormatter, - parent_is_conditional: bool, - ) -> FormatResult { - let (head, body) = match self { - Conditional::Expression(_) => ( - self.format_head(formatter)?, - self.format_body(formatter, parent_is_conditional)?, - ), - Conditional::Type(_) => ( - self.format_head(formatter)?, - self.format_body(formatter, parent_is_conditional)?, - ), - }; - - formatted![formatter, [head, body]] - } - - fn format_head(&self, formatter: &JsFormatter) -> FormatResult { + fn format_head(&self, f: &mut JsFormatter) -> FormatResult<()> { match self { Conditional::Expression(expr) => { - formatted![formatter, [expr.test()?.format(), space_token(),]] + write![f, [expr.test()?.format(), space_token(),]] } - Conditional::Type(t) => formatted![ - formatter, + Conditional::Type(t) => write![ + f, [ t.check_type()?.format(), space_token(), @@ -86,64 +68,77 @@ impl Conditional { } } - fn format_body( - &self, - formatter: &JsFormatter, - parent_is_conditional: bool, - ) -> FormatResult { - let mut left_or_right_is_conditional = false; + fn format_body(&self, f: &mut JsFormatter, parent_is_conditional: bool) -> FormatResult<()> { let consequent = self.consequent_to_conditional()?; let alternate = self.alternate_to_conditional()?; + let left_or_right_is_conditional = alternate.is_some() || consequent.is_some(); - let consequent = if let Some(consequent) = consequent { - left_or_right_is_conditional = true; - let consequent = format_conditional(consequent, formatter, true)?; - self.format_with_consequent(formatter, Some(consequent))? - } else { - self.format_with_consequent(formatter, None)? - }; + let format_consequent = + format_with(|f| self.format_with_consequent(f, consequent.as_ref())); - let alternate = if let Some(alternate) = alternate { - left_or_right_is_conditional = true; - let alternate = format_conditional(alternate, formatter, true)?; - self.format_with_alternate(formatter, Some(alternate))? - } else { - self.format_with_alternate(formatter, None)? - }; + let format_alternate = format_with(|f| self.format_with_alternate(f, alternate.as_ref())); - let body = if left_or_right_is_conditional || parent_is_conditional { - indent(formatted![ - formatter, - [hard_line_break(), consequent, hard_line_break(), alternate] - ]?) + let _body = if left_or_right_is_conditional || parent_is_conditional { + write!( + f, + [indent(&format_args![ + hard_line_break(), + format_consequent, + hard_line_break(), + format_alternate + ])] + )?; } else { - group_elements(formatted![ - formatter, - [space_token(), consequent, space_token(), alternate] - ]?) + write!( + f, + [group_elements(&format_args![ + space_token(), + format_consequent, + space_token(), + format_alternate + ])] + )?; }; - Ok(body) + + Ok(()) } fn format_with_consequent( &self, - formatter: &JsFormatter, - consequent: Option, - ) -> FormatResult { - match self { - Conditional::Expression(expr) => { - if let Some(consequent) = consequent { - formatted![ - formatter, - [ - expr.question_mark_token().format(), - space_token(), - consequent + f: &mut JsFormatter, + consequent: Option<&Conditional>, + ) -> FormatResult<()> { + match consequent { + Some(consequent) => { + let format_consequent = format_with(|f| format_conditional(consequent, f, true)); + + match self { + Conditional::Expression(expr) => { + write![ + f, + [ + expr.question_mark_token().format(), + space_token(), + format_consequent + ] ] - ] - } else { - formatted![ - formatter, + } + Conditional::Type(ty) => { + write![ + f, + [ + ty.question_mark_token().format(), + space_token(), + format_consequent + ] + ] + } + } + } + None => match self { + Conditional::Expression(expr) => { + write![ + f, [ expr.question_mark_token().format(), space_token(), @@ -151,16 +146,9 @@ impl Conditional { ] ] } - } - Conditional::Type(ty) => { - if let Some(consequent) = consequent { - formatted![ - formatter, - [ty.question_mark_token().format(), space_token(), consequent] - ] - } else { - formatted![ - formatter, + Conditional::Type(ty) => { + write![ + f, [ ty.question_mark_token().format(), space_token(), @@ -168,50 +156,53 @@ impl Conditional { ] ] } - } + }, } } fn format_with_alternate( &self, - formatter: &JsFormatter, - alternate: Option, - ) -> FormatResult { - match self { - Conditional::Expression(expr) => { - if let Some(alternate) = alternate { - formatted![ - formatter, - [expr.colon_token().format(), space_token(), alternate] - ] - } else { - formatted![ - formatter, - [ - expr.colon_token().format(), - space_token(), - expr.alternate().format() + f: &mut JsFormatter, + alternate: Option<&Conditional>, + ) -> FormatResult<()> { + match alternate { + Some(alternate) => { + let format_alternate = format_with(|f| format_conditional(alternate, f, true)); + + match self { + Conditional::Expression(expr) => { + write![ + f, + [expr.colon_token().format(), space_token(), format_alternate] ] - ] + } + Conditional::Type(ty) => { + write![ + f, + [ty.colon_token().format(), space_token(), format_alternate] + ] + } } } - Conditional::Type(ty) => { - if let Some(alternate) = alternate { - formatted![ - formatter, - [ty.colon_token().format(), space_token(), alternate] + + None => match self { + Conditional::Expression(expr) => write![ + f, + [ + expr.colon_token().format(), + space_token(), + expr.alternate().format() ] - } else { - formatted![ - formatter, - [ - ty.colon_token().format(), - space_token(), - ty.false_type().format() - ] + ], + Conditional::Type(ty) => write![ + f, + [ + ty.colon_token().format(), + space_token(), + ty.false_type().format() ] - } - } + ], + }, } } } @@ -224,9 +215,10 @@ impl Conditional { /// - [rome_js_syntax::TsConditionalType] /// - [rome_js_syntax::JsConditionalExpression] pub fn format_conditional( - conditional: Conditional, - formatter: &JsFormatter, + conditional: &Conditional, + f: &mut JsFormatter, parent_is_conditional: bool, -) -> FormatResult { - conditional.into_format_element(formatter, parent_is_conditional) +) -> FormatResult<()> { + conditional.format_head(f)?; + conditional.format_body(f, parent_is_conditional) } diff --git a/crates/rome_js_formatter/src/utils/member_chain/flatten_item.rs b/crates/rome_js_formatter/src/utils/member_chain/flatten_item.rs index fb8efa8ef13..d2cb14a8b47 100644 --- a/crates/rome_js_formatter/src/utils/member_chain/flatten_item.rs +++ b/crates/rome_js_formatter/src/utils/member_chain/flatten_item.rs @@ -141,14 +141,18 @@ impl FlattenItem { impl Debug for FlattenItem { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - FlattenItem::StaticMember(_, formatted) => write!(f, "StaticMember: {:?}", formatted), + FlattenItem::StaticMember(_, formatted) => { + std::write!(f, "StaticMember: {:?}", formatted) + } FlattenItem::CallExpression(_, formatted) => { - write!(f, "CallExpression: {:?}", formatted) + std::write!(f, "CallExpression: {:?}", formatted) } FlattenItem::ComputedExpression(_, formatted) => { - write!(f, "ComputedExpression: {:?}", formatted) + std::write!(f, "ComputedExpression: {:?}", formatted) + } + FlattenItem::Node(node, formatted) => { + std::write!(f, "{:?} {:?}", node.kind(), formatted) } - FlattenItem::Node(node, formatted) => write!(f, "{:?} {:?}", node.kind(), formatted), } } } @@ -156,9 +160,9 @@ impl Debug for FlattenItem { impl From for FormatElement { fn from(flatten_item: FlattenItem) -> Self { match flatten_item { - FlattenItem::StaticMember(_, formatted) => concat_elements(formatted), - FlattenItem::CallExpression(_, formatted) => concat_elements(formatted), - FlattenItem::ComputedExpression(_, formatted) => concat_elements(formatted), + FlattenItem::StaticMember(_, formatted) => FormatElement::from_iter(formatted), + FlattenItem::CallExpression(_, formatted) => FormatElement::from_iter(formatted), + FlattenItem::ComputedExpression(_, formatted) => FormatElement::from_iter(formatted), FlattenItem::Node(_, formatted) => formatted, } } diff --git a/crates/rome_js_formatter/src/utils/member_chain/groups.rs b/crates/rome_js_formatter/src/utils/member_chain/groups.rs index bb3032216ec..2547fbe216d 100644 --- a/crates/rome_js_formatter/src/utils/member_chain/groups.rs +++ b/crates/rome_js_formatter/src/utils/member_chain/groups.rs @@ -1,13 +1,15 @@ use crate::prelude::*; use crate::utils::member_chain::flatten_item::FlattenItem; use crate::utils::member_chain::simple_argument::SimpleArgument; + +use rome_formatter::{format, Buffer}; use rome_js_syntax::JsCallExpression; use rome_rowan::{AstSeparatedList, SyntaxResult}; use std::mem; #[derive(Clone)] /// Handles creation of groups while scanning the flatten items -pub(crate) struct Groups<'f> { +pub(crate) struct Groups { /// If the current group is inside an expression statement. /// /// This information is important when evaluating the break of the groups. @@ -17,23 +19,22 @@ pub(crate) struct Groups<'f> { /// keeps track of the current group that is being created/updated current_group: Vec, - /// instance of the formatter - formatter: &'f JsFormatter, - /// This is a threshold of when we should start breaking the groups /// /// By default, it's 2, meaning that we start breaking after the second group. cutoff: u8, + + context: JsFormatContext, } -impl<'f> Groups<'f> { - pub fn new(formatter: &'f JsFormatter, in_expression_statement: bool) -> Self { +impl Groups { + pub fn new(in_expression_statement: bool, context: JsFormatContext) -> Self { Self { - formatter, in_expression_statement, groups: Vec::new(), current_group: Vec::new(), cutoff: 2, + context, } } @@ -95,14 +96,31 @@ impl<'f> Groups<'f> { fn into_formatted_groups(self) -> Vec { self.groups .into_iter() - .map(|group| concat_elements(group.into_iter().map(|flatten_item| flatten_item.into()))) + .map(|group| { + FormatElement::from_iter(group.into_iter().map(|flatten_item| flatten_item.into())) + }) .collect() } /// Format groups on multiple lines pub fn into_joined_hard_line_groups(self) -> FormatElement { - let formatted_groups = self.into_formatted_groups(); - join_elements(hard_line_break(), formatted_groups) + let elements = format!( + JsFormatContext::default(), + [format_once(|f| { + let formatted_groups = self.into_formatted_groups(); + + f.join_with(&hard_line_break()) + .entries( + formatted_groups + .into_iter() + .map(|e| format_once(|f| f.write_element(e))), + ) + .finish() + })] + ) + .unwrap(); + + elements.into_format_element() } /// Creates two different versions of the formatted groups, one that goes in one line @@ -111,7 +129,7 @@ impl<'f> Groups<'f> { /// It's up to the printer to decide which one to use. pub fn into_format_elements(self) -> FormatElement { let formatted_groups = self.into_formatted_groups(); - concat_elements(formatted_groups) + FormatElement::from_iter(formatted_groups) } /// Filters the stack of [FlattenItem] and return only the ones that @@ -146,7 +164,7 @@ impl<'f> Groups<'f> { /// This is an heuristic needed to check when the first element of the group /// Should be part of the "head" or the "tail". fn should_not_wrap(&self, first_group: &HeadGroup) -> SyntaxResult { - let tab_with = self.formatter.context().tab_width(); + let tab_with = self.context.tab_width(); let has_computed_property = if self.groups.len() > 1 { // SAFETY: guarded by the previous check let group = &self.groups[0]; @@ -217,7 +235,7 @@ impl HeadGroup { } pub fn into_format_element(self) -> FormatElement { - concat_elements(self.items.into_iter().map(FlattenItem::into)) + FormatElement::from_iter(self.items.into_iter().map(FlattenItem::into)) } pub fn expand_group(&mut self, group: Vec) { diff --git a/crates/rome_js_formatter/src/utils/member_chain/mod.rs b/crates/rome_js_formatter/src/utils/member_chain/mod.rs index 0782a4d6069..69de5102814 100644 --- a/crates/rome_js_formatter/src/utils/member_chain/mod.rs +++ b/crates/rome_js_formatter/src/utils/member_chain/mod.rs @@ -5,6 +5,7 @@ mod simple_argument; use crate::prelude::*; use crate::utils::member_chain::flatten_item::FlattenItem; use crate::utils::member_chain::groups::{Groups, HeadGroup}; +use rome_formatter::{format_args, write, Buffer, VecBuffer}; use rome_js_syntax::{ JsCallExpression, JsComputedMemberExpression, JsExpressionStatement, JsStaticMemberExpression, }; @@ -117,16 +118,13 @@ use rome_rowan::AstNode; /// ``` /// /// [Prettier applies]: https://github.com/prettier/prettier/blob/main/src/language-js/print/member-chain.js -pub fn format_call_expression( - syntax_node: &JsSyntaxNode, - formatter: &JsFormatter, -) -> FormatResult { +pub fn format_call_expression(syntax_node: &JsSyntaxNode, f: &mut JsFormatter) -> FormatResult<()> { let mut flattened_items = vec![]; let parent_is_expression_statement = syntax_node.parent().map_or(false, |parent| { JsExpressionStatement::can_cast(parent.kind()) }); - flatten_call_expression(&mut flattened_items, syntax_node.clone(), formatter)?; + flatten_call_expression(&mut flattened_items, syntax_node.clone(), f)?; // Count the number of CallExpression in the chain, // will be used later to decide on how to format it @@ -146,8 +144,7 @@ pub fn format_call_expression( // `flattened_items` now contains only the nodes that should have a sequence of // `[ StaticMemberExpression -> AnyNode + JsCallExpression ]` - let mut rest_of_groups = - compute_groups(flattened_items, parent_is_expression_statement, formatter)?; + let mut rest_of_groups = compute_groups(flattened_items, parent_is_expression_statement, f)?; // Here we check if the first element of Groups::groups can be moved inside the head. // If so, then we extract it and concatenate it together with the head. @@ -156,7 +153,7 @@ pub fn format_call_expression( head_group.expand_group(group_to_merge); } - format_groups(calls_count, head_group, rest_of_groups) + format_groups(calls_count, head_group, rest_of_groups, f) } /// Retrieves the index where we want to calculate the first group. @@ -234,10 +231,10 @@ fn compute_first_group_index(flatten_items: &[FlattenItem]) -> usize { fn compute_groups( flatten_items: impl Iterator, in_expression_statement: bool, - formatter: &JsFormatter, + f: &JsFormatter, ) -> FormatResult { let mut has_seen_call_expression = false; - let mut groups = Groups::new(formatter, in_expression_statement); + let mut groups = Groups::new(in_expression_statement, *f.context()); for item in flatten_items { let has_trailing_comments = item.as_syntax().has_trailing_comments(); @@ -288,30 +285,31 @@ fn format_groups( calls_count: usize, head_group: HeadGroup, groups: Groups, -) -> FormatResult { + f: &mut JsFormatter, +) -> FormatResult<()> { // TODO use Alternatives once available + f.write_element(head_group.into_format_element())?; + if groups.groups_should_break(calls_count)? { - Ok(format_elements![ - head_group.into_format_element(), - indent(format_elements![ + write!( + f, + [indent(&format_args!( hard_line_break(), - groups.into_joined_hard_line_groups() - ]) - ]) + format_once(|f| { + f.write_element(groups.into_joined_hard_line_groups())?; + Ok(()) + }) + ))] + ) } else { let chain = groups.into_format_elements(); - - Ok(format_elements![ - head_group.into_format_element(), + if !chain.is_empty() { // TODO This line suffix boundary shouldn't be needed but currently is because comments // can move over node boundaries. Follow up when re-working member chain formatting - if chain.is_empty() { - empty_element() - } else { - line_suffix_boundary() - }, - chain - ]) + write!(f, [line_suffix_boundary()])?; + } + + f.write_element(chain) } } @@ -320,61 +318,71 @@ fn format_groups( fn flatten_call_expression( queue: &mut Vec, node: JsSyntaxNode, - formatter: &JsFormatter, + f: &mut JsFormatter, ) -> FormatResult<()> { match node.kind() { JsSyntaxKind::JS_CALL_EXPRESSION => { let call_expression = JsCallExpression::cast(node).unwrap(); let callee = call_expression.callee()?; - flatten_call_expression(queue, callee.syntax().clone(), formatter)?; - let formatted = vec![formatted![ - formatter, + flatten_call_expression(queue, callee.syntax().clone(), f)?; + + let mut buffer = VecBuffer::new(f.state_mut()); + write!( + buffer, [ call_expression.optional_chain_token().format(), call_expression.type_arguments().format(), call_expression.arguments().format() ] - ]?]; + )?; - queue.push(FlattenItem::CallExpression(call_expression, formatted)); + queue.push(FlattenItem::CallExpression( + call_expression, + buffer.into_vec(), + )); } JsSyntaxKind::JS_STATIC_MEMBER_EXPRESSION => { let static_member = JsStaticMemberExpression::cast(node).unwrap(); let object = static_member.object()?; - flatten_call_expression(queue, object.syntax().clone(), formatter)?; - let formatted = vec![formatted![ - formatter, + flatten_call_expression(queue, object.syntax().clone(), f)?; + + let mut buffer = VecBuffer::new(f.state_mut()); + let _formatted = write![ + buffer, [ static_member.operator_token().format(), static_member.member().format(), ] - ]?]; - queue.push(FlattenItem::StaticMember(static_member, formatted)); + ]?; + queue.push(FlattenItem::StaticMember(static_member, buffer.into_vec())); } JsSyntaxKind::JS_COMPUTED_MEMBER_EXPRESSION => { let computed_expression = JsComputedMemberExpression::cast(node).unwrap(); let object = computed_expression.object()?; - flatten_call_expression(queue, object.syntax().clone(), formatter)?; - let formatted = vec![formatted!( - formatter, + flatten_call_expression(queue, object.syntax().clone(), f)?; + + let mut buffer = VecBuffer::new(f.state_mut()); + write!( + buffer, [ computed_expression.optional_chain_token().format(), computed_expression.l_brack_token().format(), computed_expression.member().format(), computed_expression.r_brack_token().format(), ] - )?]; + )?; queue.push(FlattenItem::ComputedExpression( computed_expression, - formatted, + buffer.into_vec(), )); } _ => { - let formatted = formatted![formatter, [node.format()]]?; - queue.push(FlattenItem::Node(node, formatted)); + let mut buffer = VecBuffer::new(f.state_mut()); + write!(buffer, [node.format()])?; + queue.push(FlattenItem::Node(node, buffer.into_element())); } } diff --git a/crates/rome_js_formatter/src/utils/member_chain/simple_argument.rs b/crates/rome_js_formatter/src/utils/member_chain/simple_argument.rs index 80ebbe9579d..c0dd0001076 100644 --- a/crates/rome_js_formatter/src/utils/member_chain/simple_argument.rs +++ b/crates/rome_js_formatter/src/utils/member_chain/simple_argument.rs @@ -211,9 +211,8 @@ impl SimpleArgument { member, JsAnyObjectMember::JsShorthandPropertyObjectMember(_) ); - let is_simple = SimpleArgument::from(member.clone()).is_simple(depth + 1); let is_computed_property = - if let JsAnyObjectMember::JsPropertyObjectMember(property) = member { + if let JsAnyObjectMember::JsPropertyObjectMember(property) = &member { matches!( property.name(), Ok(JsAnyObjectMemberName::JsComputedMemberName(_)) @@ -221,6 +220,7 @@ impl SimpleArgument { } else { false }; + let is_simple = SimpleArgument::from(member).is_simple(depth + 1); !is_computed_property && (is_shorthand_property || is_simple) }) diff --git a/crates/rome_js_formatter/src/utils/mod.rs b/crates/rome_js_formatter/src/utils/mod.rs index 8d32ea2da38..b10288ec379 100644 --- a/crates/rome_js_formatter/src/utils/mod.rs +++ b/crates/rome_js_formatter/src/utils/mod.rs @@ -12,16 +12,16 @@ use crate::prelude::*; pub(crate) use binary_like_expression::{format_binary_like_expression, JsAnyBinaryLikeExpression}; pub(crate) use format_conditional::{format_conditional, Conditional}; pub(crate) use member_chain::format_call_expression; -use rome_formatter::normalize_newlines; +use rome_formatter::{normalize_newlines, write, Buffer, VecBuffer}; use rome_js_syntax::suppression::{has_suppressions_category, SuppressionCategory}; +use rome_js_syntax::JsSyntaxKind::JS_STRING_LITERAL; use rome_js_syntax::{ JsAnyClassMemberName, JsAnyExpression, JsAnyFunction, JsAnyObjectMemberName, JsAnyStatement, JsComputedMemberName, JsInitializerClause, JsLanguage, JsLiteralMemberName, - JsPrivateClassMemberName, JsTemplateElement, JsTemplateElementFields, Modifiers, - TsTemplateElement, TsTemplateElementFields, TsType, + JsPrivateClassMemberName, JsTemplateElement, Modifiers, TsTemplateElement, TsType, }; use rome_js_syntax::{JsSyntaxKind, JsSyntaxNode, JsSyntaxToken}; -use rome_rowan::{AstNode, AstNodeList}; +use rome_rowan::{AstNode, AstNodeList, SyntaxResult}; pub(crate) use simple::*; pub(crate) use string_utils::*; @@ -32,41 +32,67 @@ pub(crate) use string_utils::*; /// We can have two kind of separators: `,`, `;` or ASI. /// Because of how the grammar crafts the nodes, the parent will add the separator to the node. /// So here, we create - on purpose - an empty node. -pub(crate) fn format_type_member_separator( - separator_token: Option, - formatter: &JsFormatter, -) -> FormatElement { - if let Some(separator) = separator_token { - formatter.format_replaced(&separator, empty_element()) - } else { - empty_element() +pub(crate) struct FormatTypeMemberSeparator<'a> { + token: Option<&'a JsSyntaxToken>, +} + +impl<'a> FormatTypeMemberSeparator<'a> { + pub fn new(token: Option<&'a JsSyntaxToken>) -> Self { + Self { token } + } +} + +impl Format for FormatTypeMemberSeparator<'_> { + fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> { + if let Some(separator) = self.token { + write!(f, [format_replaced(separator, &empty_element())]) + } else { + Ok(()) + } } } /// Utility function to format the node [rome_js_syntax::JsInitializerClause] -pub(crate) fn format_initializer_clause( - formatter: &JsFormatter, - initializer: Option, -) -> FormatResult { - formatted![ - formatter, - [initializer - .format() - .with_or_empty(|initializer| { formatted![formatter, [space_token(), initializer]] })] - ] -} - -pub(crate) fn format_interpreter( - interpreter: Option, - formatter: &JsFormatter, -) -> FormatResult { - formatted![ - formatter, - [interpreter.format().with_or( - |interpreter| formatted![formatter, [interpreter, empty_line()]], - empty_element, - )] - ] +pub struct FormatInitializerClause<'a> { + initializer: Option<&'a JsInitializerClause>, +} + +impl<'a> FormatInitializerClause<'a> { + pub fn new(initializer: Option<&'a JsInitializerClause>) -> Self { + Self { initializer } + } +} + +impl Format for FormatInitializerClause<'_> { + fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> { + if let Some(initializer) = self.initializer { + write!(f, [space_token(), initializer.format()]) + } else { + Ok(()) + } + } +} + +pub struct FormatInterpreterToken<'a> { + token: Option<&'a JsSyntaxToken>, +} + +impl<'a> FormatInterpreterToken<'a> { + pub fn new(interpreter_token: Option<&'a JsSyntaxToken>) -> Self { + Self { + token: interpreter_token, + } + } +} + +impl Format for FormatInterpreterToken<'_> { + fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> { + if let Some(interpreter) = self.token { + write!(f, [interpreter.format(), empty_line()]) + } else { + Ok(()) + } + } } /// Returns true if this node contains "printable" trivias: comments @@ -122,18 +148,26 @@ pub(crate) fn has_leading_newline(node: &JsSyntaxNode) -> bool { /// /// This will place the head element inside a [hard_group_elements], but /// the body will broken out of flat printing if its a single statement -pub(crate) fn format_head_body_statement( - formatter: &JsFormatter, - head: FormatElement, - body: JsAnyStatement, -) -> FormatResult { - if matches!(body, JsAnyStatement::JsBlockStatement(_)) { - formatted![formatter, [head, space_token(), body.format(),]] - } else if matches!(body, JsAnyStatement::JsEmptyStatement(_)) { - // Force semicolon insertion if the body is empty - formatted![formatter, [head, body.format(), token(";"),]] - } else { - formatted![formatter, [head, space_token(), body.format(),]] +pub struct FormatBodyStatement<'a> { + body: &'a JsAnyStatement, +} + +impl<'a> FormatBodyStatement<'a> { + pub fn new(statement: &'a JsAnyStatement) -> Self { + Self { body: statement } + } +} + +impl Format for FormatBodyStatement<'_> { + fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> { + match self.body { + JsAnyStatement::JsEmptyStatement(body) => { + write!(f, [body.format(), token(";")]) + } + body => { + write!(f, [space_token(), body.format()]) + } + } } } @@ -156,28 +190,29 @@ where } /// Utility to format -pub(crate) fn format_template_chunk( - chunk: JsSyntaxToken, - formatter: &JsFormatter, -) -> FormatResult { +pub(crate) fn format_template_chunk(chunk: JsSyntaxToken, f: &mut JsFormatter) -> FormatResult<()> { // Per https://tc39.es/ecma262/multipage/ecmascript-language-lexical-grammar.html#sec-static-semantics-trv: // In template literals, the '\r' and '\r\n' line terminators are normalized to '\n' - Ok(formatter.format_replaced( - &chunk, - FormatElement::from(Token::from_syntax_token_cow_slice( - normalize_newlines(chunk.text_trimmed(), ['\r']), + + write!( + f, + [format_replaced( &chunk, - chunk.text_trimmed_range().start(), - )), - )) + &syntax_token_cow_slice( + normalize_newlines(chunk.text_trimmed(), ['\r']), + &chunk, + chunk.text_trimmed_range().start(), + ) + )] + ) } /// Function to format template literals and template literal types pub(crate) fn format_template_literal( literal: TemplateElement, - formatter: &JsFormatter, -) -> FormatResult { - literal.into_format_element(formatter) + formatter: &mut JsFormatter, +) -> FormatResult<()> { + write!(formatter, [literal]) } pub(crate) enum TemplateElement { @@ -185,53 +220,60 @@ pub(crate) enum TemplateElement { Ts(TsTemplateElement), } -impl TemplateElement { - pub fn into_format_element(self, formatter: &JsFormatter) -> FormatResult { +impl Format for TemplateElement { + fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> { let expression_is_plain = self.is_plain_expression()?; let has_comments = self.has_comments(); let should_hard_group = expression_is_plain && !has_comments; - let (dollar_curly_token, middle, r_curly_token) = match self { - TemplateElement::Js(template_element) => { - let JsTemplateElementFields { - dollar_curly_token, - expression, - r_curly_token, - } = template_element.as_fields(); - - let dollar_curly_token = dollar_curly_token?; - let expression = formatted![formatter, [expression.format()]]?; - let r_curly_token = r_curly_token?; - - (dollar_curly_token, expression, r_curly_token) - } - TemplateElement::Ts(template_element) => { - let TsTemplateElementFields { - ty, - r_curly_token, - dollar_curly_token, - } = template_element.as_fields(); - - let dollar_curly_token = dollar_curly_token?; - let ty = formatted![formatter, [ty.format()]]?; - let r_curly_token = r_curly_token?; - - (dollar_curly_token, ty, r_curly_token) + let content = format_with(|f| { + match self { + TemplateElement::Js(template) => { + write!(f, [template.expression().format()])?; + } + TemplateElement::Ts(template) => { + write!(f, [template.ty().format()])?; + } } - }; - let middle = format_elements![middle, line_suffix_boundary()]; + write!(f, [line_suffix_boundary()]) + }); if should_hard_group { - formatted![ - formatter, - [dollar_curly_token.format(), middle, r_curly_token.format()] - ] + write!( + f, + [ + self.dollar_curly_token().format(), + content, + self.r_curly_token().format() + ] + ) } else { - formatter - .delimited(&dollar_curly_token, middle, &r_curly_token) - .soft_block_indent() - .finish() + write!( + f, + [format_delimited( + &self.dollar_curly_token()?, + &content, + &self.r_curly_token()? + ) + .soft_block_indent()] + ) + } + } +} + +impl TemplateElement { + fn dollar_curly_token(&self) -> SyntaxResult { + match self { + TemplateElement::Js(template) => template.dollar_curly_token(), + TemplateElement::Ts(template) => template.dollar_curly_token(), + } + } + + fn r_curly_token(&self) -> SyntaxResult { + match self { + TemplateElement::Js(template) => template.r_curly_token(), + TemplateElement::Ts(template) => template.r_curly_token(), } } @@ -360,27 +402,42 @@ impl FormatPrecedence { /// Format a some code followed by an optional semicolon, and performs /// semicolon insertion if it was missing in the input source and the /// preceeding element wasn't an unknown node -pub(crate) fn format_with_semicolon( - formatter: &JsFormatter, - content: FormatElement, - semicolon: Option, -) -> FormatResult { - let is_unknown = match content.last_element() { - Some(FormatElement::Verbatim(elem)) => elem.is_unknown(), - _ => false, - }; - - formatted![ - formatter, - [ - content, - semicolon.format().or_format(if is_unknown { - empty_element - } else { - || token(";") - }) - ] - ] +pub struct FormatWithSemicolon<'a> { + content: &'a dyn Format, + semicolon: Option<&'a JsSyntaxToken>, +} + +impl<'a> FormatWithSemicolon<'a> { + pub fn new( + content: &'a dyn Format, + semicolon: Option<&'a JsSyntaxToken>, + ) -> Self { + Self { content, semicolon } + } +} + +impl Format for FormatWithSemicolon<'_> { + fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> { + let mut buffer = VecBuffer::new(f.state_mut()); + + write!(buffer, [self.content])?; + + let content = buffer.into_element(); + + let is_unknown = match content.last_element() { + Some(FormatElement::Verbatim(elem)) => elem.is_unknown(), + _ => false, + }; + + f.write_element(content)?; + + if let Some(semicolon) = self.semicolon { + write!(f, [semicolon.format()])?; + } else if !is_unknown { + write!(f, [token(";")])?; + } + Ok(()) + } } /// A call like expression is one of: @@ -405,21 +462,18 @@ pub(crate) fn is_call_like_expression(expression: &JsAnyExpression) -> bool { /// /// Once merged, the enum is used to get specific members (the literal ones) and elide /// the quotes from them, when the algorithm sees fit -#[allow(clippy::enum_variant_names)] pub(crate) enum FormatMemberName { - ComputedMemberName(JsComputedMemberName), - PrivateClassMemberName(JsPrivateClassMemberName), - LiteralMemberName(JsLiteralMemberName), + Computed(JsComputedMemberName), + Private(JsPrivateClassMemberName), + Literal(JsLiteralMemberName), } impl From for FormatMemberName { fn from(node: JsAnyClassMemberName) -> Self { match node { - JsAnyClassMemberName::JsComputedMemberName(node) => Self::ComputedMemberName(node), - JsAnyClassMemberName::JsLiteralMemberName(node) => Self::LiteralMemberName(node), - JsAnyClassMemberName::JsPrivateClassMemberName(node) => { - Self::PrivateClassMemberName(node) - } + JsAnyClassMemberName::JsComputedMemberName(node) => Self::Computed(node), + JsAnyClassMemberName::JsLiteralMemberName(node) => Self::Literal(node), + JsAnyClassMemberName::JsPrivateClassMemberName(node) => Self::Private(node), } } } @@ -427,42 +481,40 @@ impl From for FormatMemberName { impl From for FormatMemberName { fn from(node: JsAnyObjectMemberName) -> Self { match node { - JsAnyObjectMemberName::JsComputedMemberName(node) => Self::ComputedMemberName(node), - JsAnyObjectMemberName::JsLiteralMemberName(node) => Self::LiteralMemberName(node), - } - } -} - -impl FormatMemberName { - pub fn format_member_name( - &self, - formatter: &JsFormatter, - ) -> FormatResult<(FormatElement, Option)> { - match self { - FormatMemberName::ComputedMemberName(node) => { - formatted![formatter, [node.format()]].map(|element| (element, None)) - } - FormatMemberName::PrivateClassMemberName(node) => { - formatted![formatter, [node.format()]].map(|element| (element, None)) - } - FormatMemberName::LiteralMemberName(literal) => { - FormatLiteralStringToken::new(&literal.value()?, StringLiteralParentKind::Member) - .format_token(formatter) - } + JsAnyObjectMemberName::JsComputedMemberName(node) => Self::Computed(node), + JsAnyObjectMemberName::JsLiteralMemberName(node) => Self::Literal(node), } } } impl From for FormatMemberName { fn from(literal: JsLiteralMemberName) -> Self { - Self::LiteralMemberName(literal) + Self::Literal(literal) } } -impl Format for FormatMemberName { - type Context = JsFormatContext; - - fn format(&self, formatter: &JsFormatter) -> FormatResult { - self.format_member_name(formatter).map(|result| result.0) +impl Format for FormatMemberName { + fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> { + match self { + FormatMemberName::Computed(node) => { + write![f, [node.format()]] + } + FormatMemberName::Private(node) => { + write![f, [node.format()]] + } + FormatMemberName::Literal(literal) => { + let value = literal.value()?; + + if value.kind() == JS_STRING_LITERAL { + FormatLiteralStringToken::new( + &literal.value()?, + StringLiteralParentKind::Member, + ) + .fmt(f) + } else { + value.format().fmt(f) + } + } + } } } diff --git a/crates/rome_js_formatter/src/utils/string_utils.rs b/crates/rome_js_formatter/src/utils/string_utils.rs index 5bbbb05b5e2..fdfd2c603dd 100644 --- a/crates/rome_js_formatter/src/utils/string_utils.rs +++ b/crates/rome_js_formatter/src/utils/string_utils.rs @@ -68,42 +68,59 @@ impl<'token> FormatLiteralStringToken<'token> { Self { token, parent_kind } } - pub fn token(&self) -> &'token JsSyntaxToken { + fn token(&self) -> &'token JsSyntaxToken { self.token } - /// Returns the format element for the string literal - /// and the new text width if the string literal has been normalized - pub fn format_token( - &self, - formatter: &JsFormatter, - ) -> FormatResult<(FormatElement, Option)> { + pub fn clean_text(&self, context: &JsFormatContext) -> CleanedStringLiteralText { let token = self.token(); - // tokens that are don't hold any strings don't need to be processed any further - if token.kind() != JS_STRING_LITERAL { - return formatted![formatter, [self.token.format()]].map(|element| (element, None)); - } - let chosen_quote_style = formatter.context().quote_style(); + debug_assert_eq!(token.kind(), JS_STRING_LITERAL); + + let chosen_quote_style = context.quote_style(); let mut string_cleaner = LiteralStringNormaliser::new(self, chosen_quote_style); - let content = string_cleaner.normalise_text(formatter.context().source_type.into()); + let content = string_cleaner.normalise_text(context.source_type.into()); let normalized_text_width = content.width(); - let element = formatter.format_replaced( + CleanedStringLiteralText { + text: content, + width: normalized_text_width, token, - Token::from_syntax_token_cow_slice(content, token, token.text_trimmed_range().start()) - .into(), - ); + } + } +} - Ok((element, Some(normalized_text_width))) +pub struct CleanedStringLiteralText<'a> { + token: &'a JsSyntaxToken, + text: Cow<'a, str>, + width: usize, +} + +impl CleanedStringLiteralText<'_> { + pub fn width(&self) -> usize { + self.width } } -impl Format for FormatLiteralStringToken<'_> { - type Context = JsFormatContext; +impl Format for CleanedStringLiteralText<'_> { + fn fmt(&self, f: &mut Formatter) -> FormatResult<()> { + format_replaced( + self.token, + &syntax_token_cow_slice( + self.text.clone(), + self.token, + self.token.text_trimmed_range().start(), + ), + ) + .fmt(f) + } +} + +impl Format for FormatLiteralStringToken<'_> { + fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> { + let cleaned = self.clean_text(f.context()); - fn format(&self, formatter: &JsFormatter) -> FormatResult { - self.format_token(formatter).map(|result| result.0) + cleaned.fmt(f) } } @@ -222,7 +239,7 @@ impl<'token> LiteralStringNormaliser<'token> { } } - pub fn normalise_text(&mut self, file_source: SourceFileKind) -> Cow { + fn normalise_text(&mut self, file_source: SourceFileKind) -> Cow<'token, str> { let string_information = self.token.compute_string_information(self.chosen_quote); match self.token.parent_kind { StringLiteralParentKind::Expression => { @@ -247,7 +264,7 @@ impl<'token> LiteralStringNormaliser<'token> { } } - fn normalise_directive(&mut self, string_information: &StringInformation) -> Cow { + fn normalise_directive(&mut self, string_information: &StringInformation) -> Cow<'token, str> { let content = self.normalize_string(string_information); match content { Cow::Borrowed(content) => self.swap_quotes(content, string_information), @@ -293,7 +310,7 @@ impl<'token> LiteralStringNormaliser<'token> { &mut self, string_information: StringInformation, file_source: SourceFileKind, - ) -> Cow { + ) -> Cow<'token, str> { if self.can_remove_quotes(file_source) { return Cow::Owned(self.raw_content().to_string()); } @@ -315,7 +332,7 @@ impl<'token> LiteralStringNormaliser<'token> { Cow::Owned(s) => { // content is owned, meaning we allocated a new string, // so we force replacing quotes, regardless - let final_content = format!( + let final_content = std::format!( "{}{}{}", preferred_quote.as_char(), s.as_str(), @@ -531,7 +548,7 @@ impl<'token> LiteralStringNormaliser<'token> { if raw_content_has_quotes { Cow::Borrowed(original_content) } else if original_content.starts_with(other_quote) { - Cow::Owned(format!( + Cow::Owned(std::format!( "{}{}{}", preferred_quote.as_char(), content_to_use.into(), @@ -572,7 +589,7 @@ mod tests { #[quickcheck] fn to_ascii_lowercase_cow_returns_owned_when_some_chars_are_not_lowercase(txt: AsciiString) { - let txt = format!("{}A", txt); //guarantees at least one uppercase letter + let txt = std::format!("{}A", txt); //guarantees at least one uppercase letter assert!(matches!(txt.to_ascii_lowercase_cow(), Cow::Owned(s) if s == txt.to_lowercase())); } diff --git a/crates/rome_rowan/src/ast/mod.rs b/crates/rome_rowan/src/ast/mod.rs index f05573d0b81..c6ade328cb2 100644 --- a/crates/rome_rowan/src/ast/mod.rs +++ b/crates/rome_rowan/src/ast/mod.rs @@ -187,7 +187,7 @@ impl> ExactSizeIterator for AstNodeListIte impl> FusedIterator for AstNodeListIterator {} -#[derive(Clone)] +#[derive(Clone, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize))] #[cfg_attr(feature = "serde", serde(crate = "serde_crate"))] pub struct AstSeparatedElement { @@ -203,6 +203,10 @@ impl> AstSeparatedElement { } } + pub fn into_node(self) -> SyntaxResult { + self.node + } + pub fn trailing_separator(&self) -> SyntaxResult>> { match &self.trailing_separator { Ok(Some(sep)) => Ok(Some(sep)), @@ -210,6 +214,10 @@ impl> AstSeparatedElement { Err(err) => Err(*err), } } + + pub fn into_trailing_separator(self) -> SyntaxResult>> { + self.trailing_separator + } } impl Debug for AstSeparatedElement { diff --git a/crates/rome_rowan/src/cursor/trivia.rs b/crates/rome_rowan/src/cursor/trivia.rs index 42041704a73..3ac56926957 100644 --- a/crates/rome_rowan/src/cursor/trivia.rs +++ b/crates/rome_rowan/src/cursor/trivia.rs @@ -103,6 +103,7 @@ impl fmt::Display for SyntaxTrivia { } } +#[derive(Clone)] pub struct SyntaxTriviaPiecesIterator { pub(crate) raw: SyntaxTrivia, pub(crate) next_index: usize, diff --git a/crates/rome_rowan/src/syntax.rs b/crates/rome_rowan/src/syntax.rs index 6a349450251..daec6c63dcc 100644 --- a/crates/rome_rowan/src/syntax.rs +++ b/crates/rome_rowan/src/syntax.rs @@ -7,7 +7,8 @@ use std::fmt::Debug; pub use trivia::{ SyntaxTrivia, SyntaxTriviaPiece, SyntaxTriviaPieceComments, SyntaxTriviaPieceNewline, - SyntaxTriviaPieceSkipped, SyntaxTriviaPieceWhitespace, TriviaPiece, TriviaPieceKind, + SyntaxTriviaPieceSkipped, SyntaxTriviaPieceWhitespace, SyntaxTriviaPiecesIterator, TriviaPiece, + TriviaPieceKind, }; pub use element::SyntaxElement; diff --git a/crates/rome_rowan/src/syntax/trivia.rs b/crates/rome_rowan/src/syntax/trivia.rs index 7e5064e3803..dc988d840a9 100644 --- a/crates/rome_rowan/src/syntax/trivia.rs +++ b/crates/rome_rowan/src/syntax/trivia.rs @@ -517,6 +517,7 @@ pub struct SyntaxTrivia { _p: PhantomData, } +#[derive(Clone)] pub struct SyntaxTriviaPiecesIterator { iter: cursor::SyntaxTriviaPiecesIterator, _p: PhantomData, diff --git a/xtask/codegen/src/formatter.rs b/xtask/codegen/src/formatter.rs index fed29469878..73b31e74ce8 100644 --- a/xtask/codegen/src/formatter.rs +++ b/xtask/codegen/src/formatter.rs @@ -311,35 +311,34 @@ pub fn generate_formatter() { impl FormatRule<#node_id> for #format_id { type Context = JsFormatContext; - fn format(node: &#node_id, formatter: &JsFormatter) -> FormatResult { - Ok(formatter.format_list(node)) + fn fmt(node: &#node_id, f: &mut JsFormatter) -> FormatResult<()> { + f.join().entries(node.iter().formatted()).finish() } } }, NodeKind::List { .. } => quote! { use crate::prelude::*; - use crate::formatter::verbatim_node; use crate::generated::#format_id; use rome_js_syntax::#node_id; impl FormatRule<#node_id> for #format_id { type Context = JsFormatContext; - fn format(node: &#node_id, formatter: &JsFormatter) -> FormatResult { - verbatim_node(node.syntax()).format(formatter) + fn fmt(node: &#node_id, f: &mut JsFormatter) -> FormatResult<()> { + format_verbatim_node(node.syntax()).fmt(f) } } }, NodeKind::Node => { quote! { use crate::prelude::*; - use crate::{formatter::verbatim_node, FormatNodeFields}; + use crate::FormatNodeFields; use rome_rowan::AstNode; use rome_js_syntax::#node_id; impl FormatNodeFields<#node_id> for FormatNodeRule<#node_id> { - fn format_fields(node: &#node_id, formatter: &JsFormatter) -> FormatResult { - verbatim_node(node.syntax()).format(formatter) + fn fmt_fields(node: &#node_id, f: &mut JsFormatter) -> FormatResult<()> { + format_verbatim_node(node.syntax()).fmt(f) } } } @@ -347,13 +346,13 @@ pub fn generate_formatter() { NodeKind::Unknown => { quote! { use crate::prelude::*; - use crate::{FormatNodeFields, formatter::unknown_node}; + use crate::{FormatNodeFields}; use rome_rowan::AstNode; use rome_js_syntax::#node_id; impl FormatNodeFields<#node_id> for FormatNodeRule<#node_id> { - fn format_fields(node: &#node_id, formatter: &JsFormatter) -> FormatResult { - unknown_node(node.syntax()).format(formatter) + fn fmt_fields(node: &#node_id, f: &mut JsFormatter) -> FormatResult<()> { + format_unknown_node(node.syntax()).fmt(f) } } } @@ -364,7 +363,7 @@ pub fn generate_formatter() { .into_iter() .map(|variant| { let variant = Ident::new(&variant, Span::call_site()); - quote! { #node_id::#variant(node) => formatted![formatter, [node.format()]], } + quote! { #node_id::#variant(node) => node.format().fmt(f), } }) .collect(); @@ -376,7 +375,7 @@ pub fn generate_formatter() { impl FormatRule<#node_id> for #format_id { type Context = JsFormatContext; - fn format(node: &#node_id, formatter: &JsFormatter) -> FormatResult { + fn fmt(node: &#node_id, f: &mut JsFormatter) -> FormatResult<()> { match node { #( #match_arms )* } @@ -430,7 +429,7 @@ impl BoilerplateImpls { } } - impl IntoFormat for rome_js_syntax::#node_id { + impl IntoFormat for rome_js_syntax::#node_id { type Format = FormatOwnedWithRule>; fn into_format(self) -> Self::Format { @@ -451,7 +450,7 @@ impl BoilerplateImpls { } } - impl IntoFormat for rome_js_syntax::#node_id { + impl IntoFormat for rome_js_syntax::#node_id { type Format = FormatOwnedWithRule; fn into_format(self) -> Self::Format {