repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/bindings/formal_parameter.rs
crates/rome_js_formatter/src/js/bindings/formal_parameter.rs
use crate::prelude::*; use rome_formatter::write; use crate::utils::FormatInitializerClause; use crate::js::bindings::parameters::{should_hug_function_parameters, FormatAnyJsParameters}; use rome_js_syntax::JsFormalParameter; use rome_js_syntax::JsFormalParameterFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsFormalParameter; impl FormatNodeRule<JsFormalParameter> for FormatJsFormalParameter { fn fmt_fields(&self, node: &JsFormalParameter, f: &mut JsFormatter) -> FormatResult<()> { let JsFormalParameterFields { decorators, binding, question_mark_token, type_annotation, initializer, } = node.as_fields(); let content = format_with(|f| { write![ f, [ binding.format(), question_mark_token.format(), type_annotation.format() ] ] }); let is_hug_parameter = node .syntax() .grand_parent() .and_then(FormatAnyJsParameters::cast) .map_or(false, |parameters| { should_hug_function_parameters(&parameters, f.comments()).unwrap_or(false) }); if is_hug_parameter && decorators.is_empty() { write![f, [decorators.format(), content]]?; } else if decorators.is_empty() { write![f, [decorators.format(), group(&content)]]?; } else { write![f, [group(&decorators.format()), group(&content)]]?; } write![f, [FormatInitializerClause::new(initializer.as_ref())]] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/bindings/identifier_binding.rs
crates/rome_js_formatter/src/js/bindings/identifier_binding.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::JsIdentifierBinding; use rome_js_syntax::JsIdentifierBindingFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsIdentifierBinding; impl FormatNodeRule<JsIdentifierBinding> for FormatJsIdentifierBinding { fn fmt_fields(&self, node: &JsIdentifierBinding, f: &mut JsFormatter) -> FormatResult<()> { let JsIdentifierBindingFields { name_token } = node.as_fields(); write![f, [name_token.format()]] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/bindings/binding_pattern_with_default.rs
crates/rome_js_formatter/src/js/bindings/binding_pattern_with_default.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::JsBindingPatternWithDefault; use rome_js_syntax::JsBindingPatternWithDefaultFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsBindingPatternWithDefault; impl FormatNodeRule<JsBindingPatternWithDefault> for FormatJsBindingPatternWithDefault { fn fmt_fields( &self, node: &JsBindingPatternWithDefault, f: &mut JsFormatter, ) -> FormatResult<()> { let JsBindingPatternWithDefaultFields { pattern, eq_token, default, } = node.as_fields(); write![ f, [ pattern.format(), space(), eq_token.format(), space(), default.format() ] ] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/bindings/rest_parameter.rs
crates/rome_js_formatter/src/js/bindings/rest_parameter.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::JsRestParameter; use rome_js_syntax::JsRestParameterFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsRestParameter; impl FormatNodeRule<JsRestParameter> for FormatJsRestParameter { fn fmt_fields(&self, node: &JsRestParameter, f: &mut JsFormatter) -> FormatResult<()> { let JsRestParameterFields { decorators, dotdotdot_token, binding, type_annotation, } = node.as_fields(); write![ f, [ decorators.format(), dotdotdot_token.format(), binding.format(), type_annotation.format(), ] ] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/bindings/object_binding_pattern.rs
crates/rome_js_formatter/src/js/bindings/object_binding_pattern.rs
use crate::prelude::*; use crate::utils::JsObjectPatternLike; use rome_formatter::write; use rome_js_syntax::JsObjectBindingPattern; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsObjectBindingPattern; impl FormatNodeRule<JsObjectBindingPattern> for FormatJsObjectBindingPattern { fn fmt_fields(&self, node: &JsObjectBindingPattern, f: &mut JsFormatter) -> FormatResult<()> { write!(f, [JsObjectPatternLike::from(node.clone())]) } fn fmt_dangling_comments( &self, _: &JsObjectBindingPattern, _: &mut JsFormatter, ) -> FormatResult<()> { // Handled in `JsObjectPatternLike` Ok(()) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/bindings/object_binding_pattern_shorthand_property.rs
crates/rome_js_formatter/src/js/bindings/object_binding_pattern_shorthand_property.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::JsObjectBindingPatternShorthandProperty; use rome_js_syntax::JsObjectBindingPatternShorthandPropertyFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsObjectBindingPatternShorthandProperty; impl FormatNodeRule<JsObjectBindingPatternShorthandProperty> for FormatJsObjectBindingPatternShorthandProperty { fn fmt_fields( &self, node: &JsObjectBindingPatternShorthandProperty, f: &mut JsFormatter, ) -> FormatResult<()> { let JsObjectBindingPatternShorthandPropertyFields { identifier, init } = node.as_fields(); write![f, [identifier.format()]]?; if let Some(init) = init { write!(f, [space(), init.format()])?; } Ok(()) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/auxiliary/expression_snipped.rs
crates/rome_js_formatter/src/js/auxiliary/expression_snipped.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::JsExpressionSnipped; use rome_js_syntax::JsExpressionSnippedFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsExpressionSnipped; impl FormatNodeRule<JsExpressionSnipped> for FormatJsExpressionSnipped { fn fmt_fields(&self, node: &JsExpressionSnipped, f: &mut JsFormatter) -> FormatResult<()> { let JsExpressionSnippedFields { expression, eof_token, } = node.as_fields(); write![f, [expression.format(), format_removed(&eof_token?),]] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/auxiliary/catch_clause.rs
crates/rome_js_formatter/src/js/auxiliary/catch_clause.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::JsCatchClause; use rome_js_syntax::JsCatchClauseFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsCatchClause; impl FormatNodeRule<JsCatchClause> for FormatJsCatchClause { fn fmt_fields(&self, node: &JsCatchClause, f: &mut JsFormatter) -> FormatResult<()> { let JsCatchClauseFields { catch_token, declaration, body, } = node.as_fields(); write!(f, [catch_token.format(), space()])?; if let Some(declaration) = declaration { write![f, [declaration.format(), space()]]?; } write!(f, [body.format()]) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/auxiliary/reference_identifier.rs
crates/rome_js_formatter/src/js/auxiliary/reference_identifier.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::JsReferenceIdentifier; use rome_js_syntax::JsReferenceIdentifierFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsReferenceIdentifier; impl FormatNodeRule<JsReferenceIdentifier> for FormatJsReferenceIdentifier { fn fmt_fields(&self, node: &JsReferenceIdentifier, f: &mut JsFormatter) -> FormatResult<()> { let JsReferenceIdentifierFields { value_token } = node.as_fields(); write![f, [value_token.format()]] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/auxiliary/decorator.rs
crates/rome_js_formatter/src/js/auxiliary/decorator.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::{JsDecorator, JsDecoratorFields}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsDecorator; impl FormatNodeRule<JsDecorator> for FormatJsDecorator { fn fmt_fields(&self, node: &JsDecorator, f: &mut JsFormatter) -> FormatResult<()> { let JsDecoratorFields { at_token, expression, } = node.as_fields(); write![f, [at_token.format(), expression.format()]] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/auxiliary/static_modifier.rs
crates/rome_js_formatter/src/js/auxiliary/static_modifier.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::JsStaticModifier; use rome_js_syntax::JsStaticModifierFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsStaticModifier; impl FormatNodeRule<JsStaticModifier> for FormatJsStaticModifier { fn fmt_fields(&self, node: &JsStaticModifier, f: &mut JsFormatter) -> FormatResult<()> { let JsStaticModifierFields { modifier_token } = node.as_fields(); write![f, [modifier_token.format()]] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/auxiliary/module.rs
crates/rome_js_formatter/src/js/auxiliary/module.rs
use crate::prelude::*; use rome_formatter::write; use crate::utils::FormatInterpreterToken; use rome_js_syntax::JsModule; use rome_js_syntax::JsModuleFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsModule; impl FormatNodeRule<JsModule> for FormatJsModule { fn fmt_fields(&self, node: &JsModule, f: &mut JsFormatter) -> FormatResult<()> { let JsModuleFields { interpreter_token, directives, items, eof_token, } = node.as_fields(); write![ f, [ FormatInterpreterToken::new(interpreter_token.as_ref()), format_leading_comments(node.syntax()), directives.format() ] ]?; write!( f, [ items.format(), format_trailing_comments(node.syntax()), format_removed(&eof_token?), hard_line_break() ] ) } fn fmt_leading_comments(&self, _: &JsModule, _: &mut JsFormatter) -> FormatResult<()> { // Formatted as part of `fmt_fields` Ok(()) } fn fmt_dangling_comments(&self, module: &JsModule, f: &mut JsFormatter) -> FormatResult<()> { debug_assert!( !f.comments().has_dangling_comments(module.syntax()), "Module should never have dangling comments." ); Ok(()) } fn fmt_trailing_comments(&self, _: &JsModule, _: &mut JsFormatter) -> FormatResult<()> { // Formatted as part of `fmt_fields` Ok(()) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/auxiliary/else_clause.rs
crates/rome_js_formatter/src/js/auxiliary/else_clause.rs
use crate::prelude::*; use crate::utils::FormatStatementBody; use rome_formatter::write; use rome_js_syntax::JsElseClause; use rome_js_syntax::JsElseClauseFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsElseClause; impl FormatNodeRule<JsElseClause> for FormatJsElseClause { fn fmt_fields(&self, node: &JsElseClause, f: &mut JsFormatter) -> FormatResult<()> { use rome_js_syntax::AnyJsStatement::*; let JsElseClauseFields { else_token, alternate, } = node.as_fields(); let alternate = alternate?; write!( f, [ else_token.format(), group( &FormatStatementBody::new(&alternate) .with_forced_space(matches!(alternate, JsIfStatement(_))) ) ] ) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/auxiliary/finally_clause.rs
crates/rome_js_formatter/src/js/auxiliary/finally_clause.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::JsFinallyClause; use rome_js_syntax::JsFinallyClauseFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsFinallyClause; impl FormatNodeRule<JsFinallyClause> for FormatJsFinallyClause { fn fmt_fields(&self, node: &JsFinallyClause, f: &mut JsFormatter) -> FormatResult<()> { let JsFinallyClauseFields { finally_token, body, } = node.as_fields(); write![f, [finally_token.format(), space(), body.format()]] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/auxiliary/directive.rs
crates/rome_js_formatter/src/js/auxiliary/directive.rs
use crate::prelude::*; use crate::utils::{FormatLiteralStringToken, FormatStatementSemicolon, StringLiteralParentKind}; use rome_formatter::write; use rome_js_syntax::JsDirective; use rome_js_syntax::JsDirectiveFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsDirective; impl FormatNodeRule<JsDirective> for FormatJsDirective { fn fmt_fields(&self, node: &JsDirective, f: &mut JsFormatter) -> FormatResult<()> { let JsDirectiveFields { value_token, semicolon_token, } = node.as_fields(); write!( f, [ FormatLiteralStringToken::new(&value_token?, StringLiteralParentKind::Directive), FormatStatementSemicolon::new(semicolon_token.as_ref()) ] ) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/auxiliary/template_element.rs
crates/rome_js_formatter/src/js/auxiliary/template_element.rs
use crate::prelude::*; use rome_formatter::prelude::tag::Tag; use rome_formatter::{ format_args, write, CstFormatContext, FormatRuleWithOptions, RemoveSoftLinesBuffer, }; use crate::context::TabWidth; use crate::js::expressions::array_expression::FormatJsArrayExpressionOptions; use crate::js::lists::template_element_list::{TemplateElementIndention, TemplateElementLayout}; use rome_js_syntax::{ AnyJsExpression, JsSyntaxNode, JsSyntaxToken, JsTemplateElement, TsTemplateElement, }; use rome_rowan::{declare_node_union, AstNode, SyntaxResult}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsTemplateElement { options: TemplateElementOptions, } impl FormatRuleWithOptions<JsTemplateElement> for FormatJsTemplateElement { type Options = TemplateElementOptions; fn with_options(mut self, options: Self::Options) -> Self { self.options = options; self } } impl FormatNodeRule<JsTemplateElement> for FormatJsTemplateElement { fn fmt_fields( &self, node: &JsTemplateElement, formatter: &mut JsFormatter, ) -> FormatResult<()> { let element = AnyTemplateElement::from(node.clone()); FormatTemplateElement::new(element, self.options).fmt(formatter) } } declare_node_union! { pub(crate) AnyTemplateElement = JsTemplateElement | TsTemplateElement } #[derive(Debug, Copy, Clone, Default)] pub struct TemplateElementOptions { pub(crate) layout: TemplateElementLayout, /// The indention to use for this element pub(crate) indention: TemplateElementIndention, /// Does the last template chunk (text element) end with a new line? pub(crate) after_new_line: bool, } pub(crate) struct FormatTemplateElement { element: AnyTemplateElement, options: TemplateElementOptions, } impl FormatTemplateElement { pub(crate) fn new(element: AnyTemplateElement, options: TemplateElementOptions) -> Self { Self { element, options } } } impl Format<JsFormatContext> for FormatTemplateElement { fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> { let format_expression = format_with(|f| match &self.element { AnyTemplateElement::JsTemplateElement(template) => match template.expression()? { AnyJsExpression::JsArrayExpression(expression) => { let option = FormatJsArrayExpressionOptions { is_force_flat_mode: true, }; write!(f, [expression.format().with_options(option)]) } expression => write!(f, [expression.format()]), }, AnyTemplateElement::TsTemplateElement(template) => { write!(f, [template.ty().format()]) } }); let format_inner = format_with(|f: &mut JsFormatter| match self.options.layout { TemplateElementLayout::SingleLine => { let mut buffer = RemoveSoftLinesBuffer::new(f); write!(buffer, [format_expression]) } TemplateElementLayout::Fit => { use AnyJsExpression::*; let expression = self.element.expression(); // It's preferred to break after/before `${` and `}` rather than breaking in the // middle of some expressions. let indent = f .context() .comments() .has_comments(&self.element.inner_syntax()?) || matches!( expression, Some( JsStaticMemberExpression(_) | JsComputedMemberExpression(_) | JsConditionalExpression(_) | JsSequenceExpression(_) | TsAsExpression(_) | TsSatisfiesExpression(_) | JsBinaryExpression(_) | JsLogicalExpression(_) | JsInstanceofExpression(_) | JsInExpression(_) ) ); if indent { write!(f, [soft_block_indent(&format_expression)]) } else { write!(f, [format_expression]) } } }); let format_indented = format_with(|f: &mut JsFormatter| { if self.options.after_new_line { write!(f, [dedent_to_root(&format_inner)]) } else { write_with_indention( &format_inner, self.options.indention, f.options().tab_width(), f, ) } }); write!( f, [group(&format_args![ self.element.dollar_curly_token().format(), format_indented, line_suffix_boundary(), self.element.r_curly_token().format() ])] ) } } impl AnyTemplateElement { fn dollar_curly_token(&self) -> SyntaxResult<JsSyntaxToken> { match self { AnyTemplateElement::JsTemplateElement(template) => template.dollar_curly_token(), AnyTemplateElement::TsTemplateElement(template) => template.dollar_curly_token(), } } fn inner_syntax(&self) -> SyntaxResult<JsSyntaxNode> { match self { AnyTemplateElement::JsTemplateElement(template) => { template.expression().map(AstNode::into_syntax) } AnyTemplateElement::TsTemplateElement(template) => { template.ty().map(AstNode::into_syntax) } } } fn expression(&self) -> Option<AnyJsExpression> { match self { AnyTemplateElement::JsTemplateElement(template) => template.expression().ok(), AnyTemplateElement::TsTemplateElement(_) => None, } } fn r_curly_token(&self) -> SyntaxResult<JsSyntaxToken> { match self { AnyTemplateElement::JsTemplateElement(template) => template.r_curly_token(), AnyTemplateElement::TsTemplateElement(template) => template.r_curly_token(), } } } /// Writes `content` with the specified `indention`. fn write_with_indention<Content>( content: &Content, indention: TemplateElementIndention, tab_width: TabWidth, f: &mut JsFormatter, ) -> FormatResult<()> where Content: Format<JsFormatContext>, { let level = indention.level(tab_width); let spaces = indention.align(tab_width); if level == 0 && spaces == 0 { return write!(f, [content]); } // Adds as many nested `indent` elements until it reaches the desired indention level. let format_indented = format_with(|f| { for _ in 0..level { f.write_element(FormatElement::Tag(Tag::StartIndent))?; } write!(f, [content])?; for _ in 0..level { f.write_element(FormatElement::Tag(Tag::EndIndent))?; } Ok(()) }); // Adds any necessary `align` for spaces not covered by indent level. let format_aligned = format_with(|f| { if spaces == 0 { write!(f, [format_indented]) } else { write!(f, [align(spaces, &format_indented)]) } }); write!(f, [dedent_to_root(&format_aligned)]) }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/auxiliary/initializer_clause.rs
crates/rome_js_formatter/src/js/auxiliary/initializer_clause.rs
use crate::prelude::*; use crate::utils::{with_assignment_layout, AssignmentLikeLayout}; use rome_formatter::{write, FormatRuleWithOptions}; use rome_js_syntax::JsInitializerClause; use rome_js_syntax::JsInitializerClauseFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsInitializerClause { assignment_layout: Option<AssignmentLikeLayout>, } #[derive(Default, Debug)] pub(crate) struct FormatJsInitializerClauseOptions { pub(crate) assignment_layout: Option<AssignmentLikeLayout>, } impl FormatRuleWithOptions<JsInitializerClause> for FormatJsInitializerClause { type Options = FormatJsInitializerClauseOptions; fn with_options(mut self, options: Self::Options) -> Self { self.assignment_layout = options.assignment_layout; self } } impl FormatNodeRule<JsInitializerClause> for FormatJsInitializerClause { fn fmt_fields(&self, node: &JsInitializerClause, f: &mut JsFormatter) -> FormatResult<()> { let JsInitializerClauseFields { eq_token, expression, } = node.as_fields(); write![ f, [ eq_token.format(), space(), with_assignment_layout(&expression?, self.assignment_layout) ] ] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/auxiliary/case_clause.rs
crates/rome_js_formatter/src/js/auxiliary/case_clause.rs
use crate::prelude::*; use rome_formatter::{format_args, write}; use rome_js_syntax::AnyJsStatement; use rome_js_syntax::JsCaseClause; use rome_js_syntax::JsCaseClauseFields; use rome_rowan::AstNodeList; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsCaseClause; impl FormatNodeRule<JsCaseClause> for FormatJsCaseClause { fn fmt_fields(&self, node: &JsCaseClause, f: &mut JsFormatter) -> FormatResult<()> { let JsCaseClauseFields { case_token, test, colon_token, consequent, } = node.as_fields(); write!( f, [ case_token.format(), space(), test.format(), colon_token.format() ] )?; let is_first_child_block_stmt = matches!( consequent.iter().next(), Some(AnyJsStatement::JsBlockStatement(_)) ); 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 write!(f, [hard_line_break()]) } else if is_first_child_block_stmt { write![f, [space(), consequent.format()]] } else { // no line break needed after because it is added by the indent in the switch statement write!( f, [indent(&format_args![ hard_line_break(), consequent.format() ])] ) } } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/auxiliary/function_body.rs
crates/rome_js_formatter/src/js/auxiliary/function_body.rs
use crate::prelude::*; use rome_formatter::{format_args, write}; use rome_js_syntax::JsFunctionBody; use rome_js_syntax::JsFunctionBodyFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsFunctionBody; impl FormatNodeRule<JsFunctionBody> for FormatJsFunctionBody { fn fmt_fields(&self, node: &JsFunctionBody, f: &mut JsFormatter) -> FormatResult<()> { let JsFunctionBodyFields { l_curly_token, directives, statements, r_curly_token, } = node.as_fields(); let r_curly_token = r_curly_token?; if statements.is_empty() && directives.is_empty() { write!( f, [ l_curly_token.format(), format_dangling_comments(node.syntax()).with_block_indent(), r_curly_token.format() ] ) } else { write!( f, [ l_curly_token.format(), block_indent(&format_args![directives.format(), statements.format()]), r_curly_token.format(), ] ) } } fn fmt_dangling_comments(&self, _: &JsFunctionBody, _: &mut JsFormatter) -> FormatResult<()> { // Formatted as part of `fmt_fields` Ok(()) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/auxiliary/default_clause.rs
crates/rome_js_formatter/src/js/auxiliary/default_clause.rs
use crate::prelude::*; use rome_formatter::{format_args, write}; use rome_js_syntax::JsDefaultClause; use rome_js_syntax::{AnyJsStatement, JsDefaultClauseFields}; use rome_rowan::AstNodeList; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsDefaultClause; impl FormatNodeRule<JsDefaultClause> for FormatJsDefaultClause { fn fmt_fields(&self, node: &JsDefaultClause, f: &mut JsFormatter) -> FormatResult<()> { let JsDefaultClauseFields { default_token, colon_token, consequent, } = node.as_fields(); let first_child_is_block_stmt = matches!( consequent.iter().next(), Some(AnyJsStatement::JsBlockStatement(_)) ); write!(f, [default_token.format(), colon_token.format()])?; if f.comments().has_dangling_comments(node.syntax()) { write!(f, [space(), format_dangling_comments(node.syntax())])?; } if consequent.is_empty() { write!(f, [hard_line_break()]) } else if first_child_is_block_stmt { write!(f, [space(), consequent.format()]) } else { // no line break needed after because it is added by the indent in the switch statement write!( f, [indent(&format_args!( hard_line_break(), consequent.format() ))] ) } } fn fmt_dangling_comments(&self, _: &JsDefaultClause, _: &mut JsFormatter) -> FormatResult<()> { // Handled inside of `fmt_fields` Ok(()) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/auxiliary/mod.rs
crates/rome_js_formatter/src/js/auxiliary/mod.rs
//! This is a generated file. Don't modify it by hand! Run 'cargo codegen formatter' to re-generate the file. pub(crate) mod accessor_modifier; pub(crate) mod array_hole; pub(crate) mod case_clause; pub(crate) mod catch_clause; pub(crate) mod decorator; pub(crate) mod default_clause; pub(crate) mod directive; pub(crate) mod else_clause; pub(crate) mod expression_snipped; pub(crate) mod finally_clause; pub(crate) mod function_body; pub(crate) mod initializer_clause; pub(crate) mod module; pub(crate) mod name; pub(crate) mod private_name; pub(crate) mod reference_identifier; pub(crate) mod script; pub(crate) mod spread; pub(crate) mod static_modifier; pub(crate) mod template_chunk_element; pub(crate) mod template_element; pub(crate) mod variable_declaration_clause; pub(crate) mod variable_declarator;
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/auxiliary/template_chunk_element.rs
crates/rome_js_formatter/src/js/auxiliary/template_chunk_element.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::{JsSyntaxToken, JsTemplateChunkElement, TsTemplateChunkElement}; use rome_rowan::{declare_node_union, SyntaxResult}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsTemplateChunkElement; impl FormatNodeRule<JsTemplateChunkElement> for FormatJsTemplateChunkElement { fn fmt_fields( &self, node: &JsTemplateChunkElement, formatter: &mut JsFormatter, ) -> FormatResult<()> { AnyTemplateChunkElement::from(node.clone()).fmt(formatter) } } declare_node_union! { pub(crate) AnyTemplateChunkElement = JsTemplateChunkElement | TsTemplateChunkElement } impl AnyTemplateChunkElement { pub(crate) fn template_chunk_token(&self) -> SyntaxResult<JsSyntaxToken> { match self { AnyTemplateChunkElement::JsTemplateChunkElement(chunk) => chunk.template_chunk_token(), AnyTemplateChunkElement::TsTemplateChunkElement(chunk) => chunk.template_chunk_token(), } } } impl Format<JsFormatContext> for AnyTemplateChunkElement { fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> { let chunk = self.template_chunk_token()?; write!( f, [format_replaced( &chunk, &syntax_token_cow_slice( // 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' normalize_newlines(chunk.text_trimmed(), ['\r']), &chunk, chunk.text_trimmed_range().start(), ) )] ) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/auxiliary/name.rs
crates/rome_js_formatter/src/js/auxiliary/name.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::JsName; use rome_js_syntax::JsNameFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsName; impl FormatNodeRule<JsName> for FormatJsName { fn fmt_fields(&self, node: &JsName, f: &mut JsFormatter) -> FormatResult<()> { let JsNameFields { value_token } = node.as_fields(); write![f, [value_token.format()]] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/auxiliary/script.rs
crates/rome_js_formatter/src/js/auxiliary/script.rs
use crate::prelude::*; use crate::utils::FormatInterpreterToken; use rome_formatter::write; use rome_js_syntax::JsScript; use rome_js_syntax::JsScriptFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsScript; impl FormatNodeRule<JsScript> for FormatJsScript { fn fmt_fields(&self, node: &JsScript, f: &mut JsFormatter) -> FormatResult<()> { let JsScriptFields { interpreter_token, directives, statements, eof_token, } = node.as_fields(); write![ f, [ FormatInterpreterToken::new(interpreter_token.as_ref()), format_leading_comments(node.syntax()), directives.format(), ] ]?; write![ f, [ statements.format(), format_trailing_comments(node.syntax()), format_removed(&eof_token?), hard_line_break() ] ] } fn fmt_leading_comments(&self, _: &JsScript, _: &mut JsFormatter) -> FormatResult<()> { // Formatted as part of `fmt_fields` Ok(()) } fn fmt_dangling_comments(&self, node: &JsScript, f: &mut JsFormatter) -> FormatResult<()> { debug_assert!( !f.comments().has_dangling_comments(node.syntax()), "Scrip should never have dangling comments." ); Ok(()) } fn fmt_trailing_comments(&self, _: &JsScript, _: &mut JsFormatter) -> FormatResult<()> { // Formatted as part of `fmt_fields` Ok(()) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/auxiliary/spread.rs
crates/rome_js_formatter/src/js/auxiliary/spread.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::JsSpread; use rome_js_syntax::JsSpreadFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsSpread; impl FormatNodeRule<JsSpread> for FormatJsSpread { fn fmt_fields(&self, node: &JsSpread, f: &mut JsFormatter) -> FormatResult<()> { let JsSpreadFields { dotdotdot_token, argument, } = node.as_fields(); write![f, [dotdotdot_token.format(), argument.format()]] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/auxiliary/private_name.rs
crates/rome_js_formatter/src/js/auxiliary/private_name.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::JsPrivateName; use rome_js_syntax::JsPrivateNameFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsPrivateName; impl FormatNodeRule<JsPrivateName> for FormatJsPrivateName { fn fmt_fields(&self, node: &JsPrivateName, f: &mut JsFormatter) -> FormatResult<()> { let JsPrivateNameFields { hash_token, value_token, } = node.as_fields(); write![f, [hash_token.format(), value_token.format()]] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/auxiliary/variable_declaration_clause.rs
crates/rome_js_formatter/src/js/auxiliary/variable_declaration_clause.rs
use crate::prelude::*; use crate::utils::FormatStatementSemicolon; use rome_formatter::write; use rome_js_syntax::JsVariableDeclarationClause; use rome_js_syntax::JsVariableDeclarationClauseFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsVariableDeclarationClause; impl FormatNodeRule<JsVariableDeclarationClause> for FormatJsVariableDeclarationClause { fn fmt_fields( &self, node: &JsVariableDeclarationClause, f: &mut JsFormatter, ) -> FormatResult<()> { let JsVariableDeclarationClauseFields { declaration, semicolon_token, } = node.as_fields(); write!( f, [ declaration.format(), FormatStatementSemicolon::new(semicolon_token.as_ref()) ] ) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/auxiliary/array_hole.rs
crates/rome_js_formatter/src/js/auxiliary/array_hole.rs
use crate::prelude::*; use rome_js_syntax::JsArrayHole; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsArrayHole; impl FormatNodeRule<JsArrayHole> for FormatJsArrayHole { fn fmt_fields(&self, _: &JsArrayHole, _: &mut JsFormatter) -> FormatResult<()> { Ok(()) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/auxiliary/variable_declarator.rs
crates/rome_js_formatter/src/js/auxiliary/variable_declarator.rs
use crate::prelude::*; use crate::utils::AnyJsAssignmentLike; use rome_formatter::write; use rome_js_syntax::JsVariableDeclarator; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsVariableDeclarator; impl FormatNodeRule<JsVariableDeclarator> for FormatJsVariableDeclarator { fn fmt_fields(&self, node: &JsVariableDeclarator, f: &mut JsFormatter) -> FormatResult<()> { write![f, [AnyJsAssignmentLike::from(node.clone())]] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/auxiliary/accessor_modifier.rs
crates/rome_js_formatter/src/js/auxiliary/accessor_modifier.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::{JsAccessorModifier, JsAccessorModifierFields}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsAccessorModifier; impl FormatNodeRule<JsAccessorModifier> for FormatJsAccessorModifier { fn fmt_fields(&self, node: &JsAccessorModifier, f: &mut JsFormatter) -> FormatResult<()> { let JsAccessorModifierFields { modifier_token } = node.as_fields(); write![f, [modifier_token.format()]] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/template_expression.rs
crates/rome_js_formatter/src/js/expressions/template_expression.rs
use crate::prelude::*; use rome_formatter::write; use crate::js::expressions::static_member_expression::member_chain_callee_needs_parens; use crate::js::lists::template_element_list::FormatJsTemplateElementListOptions; use crate::parentheses::NeedsParentheses; use crate::utils::test_call::is_test_each_pattern; use rome_js_syntax::{AnyJsExpression, JsSyntaxNode, JsTemplateExpression, TsTemplateLiteralType}; use rome_js_syntax::{JsSyntaxToken, TsTypeArguments}; use rome_rowan::{declare_node_union, SyntaxResult}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsTemplateExpression; impl FormatNodeRule<JsTemplateExpression> for FormatJsTemplateExpression { fn fmt_fields(&self, node: &JsTemplateExpression, f: &mut JsFormatter) -> FormatResult<()> { AnyJsTemplate::from(node.clone()).fmt(f) } fn needs_parentheses(&self, item: &JsTemplateExpression) -> bool { item.needs_parentheses() } } declare_node_union! { AnyJsTemplate = JsTemplateExpression | TsTemplateLiteralType } impl Format<JsFormatContext> for AnyJsTemplate { fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> { write!( f, [ self.tag().format(), self.type_arguments().format(), line_suffix_boundary(), self.l_tick_token().format(), ] )?; self.write_elements(f)?; write!(f, [self.r_tick_token().format()]) } } impl AnyJsTemplate { fn tag(&self) -> Option<AnyJsExpression> { match self { AnyJsTemplate::JsTemplateExpression(template) => template.tag(), AnyJsTemplate::TsTemplateLiteralType(_) => None, } } fn type_arguments(&self) -> Option<TsTypeArguments> { match self { AnyJsTemplate::JsTemplateExpression(template) => template.type_arguments(), AnyJsTemplate::TsTemplateLiteralType(_) => None, } } fn l_tick_token(&self) -> SyntaxResult<JsSyntaxToken> { match self { AnyJsTemplate::JsTemplateExpression(template) => template.l_tick_token(), AnyJsTemplate::TsTemplateLiteralType(template) => template.l_tick_token(), } } fn write_elements(&self, f: &mut JsFormatter) -> FormatResult<()> { match self { AnyJsTemplate::JsTemplateExpression(template) => { let is_test_each_pattern = is_test_each_pattern(template); let options = FormatJsTemplateElementListOptions { is_test_each_pattern, }; write!(f, [template.elements().format().with_options(options)]) } AnyJsTemplate::TsTemplateLiteralType(template) => { write!(f, [template.elements().format()]) } } } fn r_tick_token(&self) -> SyntaxResult<JsSyntaxToken> { match self { AnyJsTemplate::JsTemplateExpression(template) => template.r_tick_token(), AnyJsTemplate::TsTemplateLiteralType(template) => template.r_tick_token(), } } } /// `TemplateLiteral`'s are `PrimaryExpression's that never need parentheses. impl NeedsParentheses for JsTemplateExpression { fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool { if self.tag().is_some() { member_chain_callee_needs_parens(self.clone().into(), parent) } else { false } } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/sequence_expression.rs
crates/rome_js_formatter/src/js/expressions/sequence_expression.rs
use crate::prelude::*; use crate::parentheses::NeedsParentheses; use rome_formatter::{format_args, write}; use rome_js_syntax::JsSyntaxKind::JS_SEQUENCE_EXPRESSION; use rome_js_syntax::{ JsSequenceExpression, JsSequenceExpressionFields, JsSyntaxKind, JsSyntaxNode, }; use rome_rowan::AstNode; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsSequenceExpression; impl FormatNodeRule<JsSequenceExpression> for FormatJsSequenceExpression { fn fmt_fields(&self, node: &JsSequenceExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsSequenceExpressionFields { left, comma_token, right, } = node.as_fields(); let mut is_nested = false; let mut first_non_sequence_or_paren_parent = None; // Skip 1 because ancestor starts with the current node but we're interested in the parent for parent in node.syntax().ancestors().skip(1) { if parent.kind() == JS_SEQUENCE_EXPRESSION { is_nested = true; } else { first_non_sequence_or_paren_parent = Some(parent); break; } } let format_inner = format_with(|f| { if let Some(parent) = &first_non_sequence_or_paren_parent { if matches!( parent.kind(), JsSyntaxKind::JS_EXPRESSION_STATEMENT | JsSyntaxKind::JS_FOR_STATEMENT ) { return write!( f, [ left.format(), comma_token.format(), line_suffix_boundary(), indent(&format_args![soft_line_break_or_space(), right.format()]) ] ); } } write!( f, [ left.format(), comma_token.format(), line_suffix_boundary(), soft_line_break_or_space(), right.format() ] ) }); if is_nested { write!(f, [format_inner]) } else { write!(f, [group(&format_inner)]) } } fn needs_parentheses(&self, item: &JsSequenceExpression) -> bool { item.needs_parentheses() } } impl NeedsParentheses for JsSequenceExpression { fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool { !matches!( parent.kind(), JsSyntaxKind::JS_RETURN_STATEMENT | // There's a precedence for writing `x++, y++` JsSyntaxKind::JS_FOR_STATEMENT | JsSyntaxKind::JS_EXPRESSION_STATEMENT | JsSyntaxKind::JS_SEQUENCE_EXPRESSION | // Handled as part of the arrow function formatting JsSyntaxKind::JS_ARROW_FUNCTION_EXPRESSION ) } } #[cfg(test)] mod tests { use crate::assert_not_needs_parentheses; use rome_js_syntax::JsSequenceExpression; #[test] fn needs_parentheses() { assert_not_needs_parentheses!("function test() { return a, b }", JsSequenceExpression); assert_not_needs_parentheses!("for (let i, x; i++, x++;) {}", JsSequenceExpression); assert_not_needs_parentheses!("a, b;", JsSequenceExpression); assert_not_needs_parentheses!("a, b, c", JsSequenceExpression[0]); assert_not_needs_parentheses!("a, b, c", JsSequenceExpression[1]); assert_not_needs_parentheses!("a => a, b", JsSequenceExpression); } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/conditional_expression.rs
crates/rome_js_formatter/src/js/expressions/conditional_expression.rs
use crate::prelude::*; use crate::utils::{AnyJsConditional, ConditionalJsxChain}; use rome_formatter::FormatRuleWithOptions; use crate::parentheses::{ is_binary_like_left_or_right, is_conditional_test, is_spread, update_or_lower_expression_needs_parentheses, NeedsParentheses, }; use rome_js_syntax::{JsConditionalExpression, JsSyntaxKind, JsSyntaxNode}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsConditionalExpression { jsx_chain: ConditionalJsxChain, } impl FormatRuleWithOptions<JsConditionalExpression> for FormatJsConditionalExpression { type Options = ConditionalJsxChain; fn with_options(mut self, options: Self::Options) -> Self { self.jsx_chain = options; self } } impl FormatNodeRule<JsConditionalExpression> for FormatJsConditionalExpression { fn fmt_fields( &self, node: &JsConditionalExpression, formatter: &mut JsFormatter, ) -> FormatResult<()> { AnyJsConditional::from(node.clone()) .format() .with_options(self.jsx_chain) .fmt(formatter) } fn needs_parentheses(&self, item: &JsConditionalExpression) -> bool { item.needs_parentheses() } } impl NeedsParentheses for JsConditionalExpression { fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool { match parent.kind() { JsSyntaxKind::JS_UNARY_EXPRESSION | JsSyntaxKind::JS_AWAIT_EXPRESSION | JsSyntaxKind::TS_TYPE_ASSERTION_EXPRESSION | JsSyntaxKind::TS_AS_EXPRESSION | JsSyntaxKind::TS_SATISFIES_EXPRESSION => true, _ => { is_conditional_test(self.syntax(), parent) || update_or_lower_expression_needs_parentheses(self.syntax(), parent) || is_binary_like_left_or_right(self.syntax(), parent) || is_spread(self.syntax(), parent) } } } } #[cfg(test)] mod tests { use crate::{assert_needs_parentheses, assert_not_needs_parentheses}; use rome_js_syntax::{JsConditionalExpression, JsFileSource}; #[test] fn needs_parentheses() { assert_needs_parentheses!("((a ? b : c)).member", JsConditionalExpression); assert_needs_parentheses!("(a ? b : c).member", JsConditionalExpression); assert_needs_parentheses!("(a ? b : c)[member]", JsConditionalExpression); assert_not_needs_parentheses!("object[(a ? b : c)]", JsConditionalExpression); assert_needs_parentheses!("new (true ? A : B)()", JsConditionalExpression); assert_not_needs_parentheses!("new A(a ? b : c)", JsConditionalExpression); assert_needs_parentheses!("(true ? A : B)()", JsConditionalExpression); assert_not_needs_parentheses!("call(a ? b : c)", JsConditionalExpression); assert_needs_parentheses!( "(a ? b : c)`tagged template literal`", JsConditionalExpression ); assert_not_needs_parentheses!("tag`content ${a ? b : c}`", JsConditionalExpression); assert_needs_parentheses!("-(a ? b : c)", JsConditionalExpression); assert_needs_parentheses!("[...(a ? b : c)]", JsConditionalExpression); assert_needs_parentheses!("({...(a ? b : c)})", JsConditionalExpression); assert_needs_parentheses!("call(...(a ? b : c))", JsConditionalExpression); assert_needs_parentheses!("a + (b ? c : d)", JsConditionalExpression); assert_needs_parentheses!("(a ? b : c) + d", JsConditionalExpression); assert_needs_parentheses!("a instanceof (b ? c : d)", JsConditionalExpression); assert_needs_parentheses!("(a ? b : c) instanceof d", JsConditionalExpression); assert_needs_parentheses!("a in (b ? c : d)", JsConditionalExpression); assert_needs_parentheses!("(a ? b : c) in d", JsConditionalExpression); assert_needs_parentheses!("a && (b ? c : d)", JsConditionalExpression); assert_needs_parentheses!("(a ? b : c) && d", JsConditionalExpression); assert_needs_parentheses!("await (a ? b : c)", JsConditionalExpression); assert_needs_parentheses!( "<a {...(a ? b : c)} />", JsConditionalExpression, JsFileSource::tsx() ); assert_needs_parentheses!("(a ? b : c) as number;", JsConditionalExpression); assert_needs_parentheses!("<number>(a ? b : c);", JsConditionalExpression); assert_needs_parentheses!("class Test extends (a ? B : C) {}", JsConditionalExpression); assert_needs_parentheses!("(a ? B : C)!", JsConditionalExpression); assert_not_needs_parentheses!("a ? b : c", JsConditionalExpression); assert_not_needs_parentheses!("(a ? b : c)", JsConditionalExpression); assert_needs_parentheses!("({ a: 'test' } ? B : C)!", JsConditionalExpression); assert_not_needs_parentheses!( "console.log({ a: 'test' } ? B : C )", JsConditionalExpression ); assert_not_needs_parentheses!("a ? b : c", JsConditionalExpression); } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/regex_literal_expression.rs
crates/rome_js_formatter/src/js/expressions/regex_literal_expression.rs
use crate::prelude::*; use rome_formatter::write; use crate::parentheses::NeedsParentheses; use rome_js_syntax::JsRegexLiteralExpressionFields; use rome_js_syntax::{JsRegexLiteralExpression, JsSyntaxNode}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsRegexLiteralExpression; impl FormatNodeRule<JsRegexLiteralExpression> for FormatJsRegexLiteralExpression { fn fmt_fields(&self, 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(); // find end slash, so we could split our regex literal to two part `body`: raw_string[0..end_slash_pos + 1] and `flags`: raw_string[end_slash_pos + 1..] // reference https://tc39.es/ecma262/#prod-RegularExpressionLiteral let ends_with_slash = trimmed_raw_string.ends_with('/'); // this means that we have a regex literal with no flags if ends_with_slash { return write!(f, [value_token.format()]); } // SAFETY: a valid regex literal must have a end slash let end_slash_pos = trimmed_raw_string.rfind('/').unwrap(); let mut flag_char_vec = trimmed_raw_string[end_slash_pos + 1..] .chars() .collect::<Vec<_>>(); flag_char_vec.sort_unstable(); let sorted_flag_string = flag_char_vec.iter().collect::<String>(); 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 )), &value_token, value_token.text_trimmed_range().start(), ); write!(f, [format_replaced(&value_token, &sorted_regex_literal)]) } fn needs_parentheses(&self, item: &JsRegexLiteralExpression) -> bool { item.needs_parentheses() } } impl NeedsParentheses for JsRegexLiteralExpression { #[inline(always)] fn needs_parentheses(&self) -> bool { false } #[inline(always)] fn needs_parentheses_with_parent(&self, _parent: &JsSyntaxNode) -> bool { false } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/new_target_expression.rs
crates/rome_js_formatter/src/js/expressions/new_target_expression.rs
use crate::prelude::*; use crate::parentheses::NeedsParentheses; use rome_formatter::write; use rome_js_syntax::JsNewTargetExpressionFields; use rome_js_syntax::{JsNewTargetExpression, JsSyntaxNode}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsNewTargetExpression; impl FormatNodeRule<JsNewTargetExpression> for FormatJsNewTargetExpression { fn fmt_fields(&self, node: &JsNewTargetExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsNewTargetExpressionFields { new_token, dot_token, target_token, } = node.as_fields(); write![ f, [ new_token.format(), dot_token.format(), target_token.format(), ] ] } fn needs_parentheses(&self, item: &JsNewTargetExpression) -> bool { item.needs_parentheses() } } impl NeedsParentheses for JsNewTargetExpression { fn needs_parentheses(&self) -> bool { false } fn needs_parentheses_with_parent(&self, _parent: &JsSyntaxNode) -> bool { false } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/bigint_literal_expression.rs
crates/rome_js_formatter/src/js/expressions/bigint_literal_expression.rs
use rome_formatter::token::string::ToAsciiLowercaseCow; use rome_formatter::write; use std::borrow::Cow; use crate::prelude::*; use crate::parentheses::NeedsParentheses; use rome_js_syntax::JsBigintLiteralExpressionFields; use rome_js_syntax::{JsBigintLiteralExpression, JsSyntaxNode}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsBigintLiteralExpression; impl FormatNodeRule<JsBigintLiteralExpression> for FormatJsBigintLiteralExpression { fn fmt_fields( &self, 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(_) => write![f, [value_token.format()]], Cow::Owned(lowercase) => { write!( f, [format_replaced( &value_token, &dynamic_text(&lowercase, value_token.text_trimmed_range().start()) )] ) } } } fn needs_parentheses(&self, item: &JsBigintLiteralExpression) -> bool { item.needs_parentheses() } } impl NeedsParentheses for JsBigintLiteralExpression { #[inline(always)] fn needs_parentheses(&self) -> bool { false } #[inline(always)] fn needs_parentheses_with_parent(&self, _parent: &JsSyntaxNode) -> bool { false } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/unary_expression.rs
crates/rome_js_formatter/src/js/expressions/unary_expression.rs
use crate::prelude::*; use rome_formatter::{format_args, write}; use crate::parentheses::{unary_like_expression_needs_parentheses, NeedsParentheses}; use rome_js_syntax::JsSyntaxNode; use rome_js_syntax::JsUnaryExpression; use rome_js_syntax::{JsUnaryExpressionFields, JsUnaryOperator}; use rome_rowan::match_ast; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsUnaryExpression; impl FormatNodeRule<JsUnaryExpression> for FormatJsUnaryExpression { fn fmt_fields(&self, node: &JsUnaryExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsUnaryExpressionFields { operator_token, argument, } = node.as_fields(); let operation = node.operator()?; let operator_token = operator_token?; let argument = argument?; write!(f, [operator_token.format()])?; let is_keyword_operator = matches!( operation, JsUnaryOperator::Delete | JsUnaryOperator::Void | JsUnaryOperator::Typeof ); if is_keyword_operator { write!(f, [space()])?; } if f.comments().has_comments(argument.syntax()) && !f.comments().is_suppressed(argument.syntax()) { write!( f, [group(&format_args![ text("("), soft_block_indent(&argument.format()), text(")") ])] ) } else { write![f, [argument.format()]] } } fn needs_parentheses(&self, item: &JsUnaryExpression) -> bool { item.needs_parentheses() } } impl NeedsParentheses for JsUnaryExpression { fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool { match_ast! { match parent { JsUnaryExpression(parent_unary) => { let parent_operator = parent_unary.operator(); let operator = self.operator(); matches!(operator, Ok(JsUnaryOperator::Plus | JsUnaryOperator::Minus)) && parent_operator == operator }, _ => { unary_like_expression_needs_parentheses(self.syntax(), parent) } } } } } #[cfg(test)] mod tests { use crate::{assert_needs_parentheses, assert_not_needs_parentheses}; use rome_js_syntax::JsUnaryExpression; #[test] fn needs_parentheses() { assert_needs_parentheses!("class A extends (!B) {}", JsUnaryExpression); assert_needs_parentheses!("(+a).b", JsUnaryExpression); assert_needs_parentheses!("(+a)[b]", JsUnaryExpression); assert_not_needs_parentheses!("a[+b]", JsUnaryExpression); assert_needs_parentheses!("(+a)`template`", JsUnaryExpression); assert_needs_parentheses!("(+a)()", JsUnaryExpression); assert_needs_parentheses!("new (+a)()", JsUnaryExpression); assert_needs_parentheses!("(+a)!", JsUnaryExpression); assert_needs_parentheses!("(+a) ** 3", JsUnaryExpression); assert_not_needs_parentheses!("(+a) + 3", JsUnaryExpression); } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/boolean_literal_expression.rs
crates/rome_js_formatter/src/js/expressions/boolean_literal_expression.rs
use crate::prelude::*; use crate::parentheses::NeedsParentheses; use rome_formatter::write; use rome_js_syntax::JsBooleanLiteralExpressionFields; use rome_js_syntax::{JsBooleanLiteralExpression, JsSyntaxNode}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsBooleanLiteralExpression; impl FormatNodeRule<JsBooleanLiteralExpression> for FormatJsBooleanLiteralExpression { fn fmt_fields( &self, node: &JsBooleanLiteralExpression, f: &mut JsFormatter, ) -> FormatResult<()> { let JsBooleanLiteralExpressionFields { value_token } = node.as_fields(); write![f, [value_token.format()]] } fn needs_parentheses(&self, item: &JsBooleanLiteralExpression) -> bool { item.needs_parentheses() } } impl NeedsParentheses for JsBooleanLiteralExpression { #[inline(always)] fn needs_parentheses(&self) -> bool { false } #[inline(always)] fn needs_parentheses_with_parent(&self, _parent: &JsSyntaxNode) -> bool { false } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/string_literal_expression.rs
crates/rome_js_formatter/src/js/expressions/string_literal_expression.rs
use crate::prelude::*; use crate::utils::{FormatLiteralStringToken, StringLiteralParentKind}; use crate::parentheses::NeedsParentheses; use rome_js_syntax::JsStringLiteralExpressionFields; use rome_js_syntax::{JsExpressionStatement, JsSyntaxKind}; use rome_js_syntax::{JsStringLiteralExpression, JsSyntaxNode}; use rome_rowan::AstNode; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsStringLiteralExpression; impl FormatNodeRule<JsStringLiteralExpression> for FormatJsStringLiteralExpression { fn fmt_fields( &self, node: &JsStringLiteralExpression, f: &mut JsFormatter, ) -> FormatResult<()> { let JsStringLiteralExpressionFields { value_token } = node.as_fields(); let value_token = value_token?; let formatted = FormatLiteralStringToken::new(&value_token, StringLiteralParentKind::Expression); formatted.fmt(f) } fn needs_parentheses(&self, item: &JsStringLiteralExpression) -> bool { item.needs_parentheses() } } impl NeedsParentheses for JsStringLiteralExpression { fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool { if let Some(expression_statement) = JsExpressionStatement::cast(parent.clone()) { expression_statement .syntax() .parent() .map_or(false, |grand_parent| { matches!( grand_parent.kind(), JsSyntaxKind::JS_STATEMENT_LIST | JsSyntaxKind::JS_MODULE_ITEM_LIST ) }) } else { false } } } #[cfg(test)] mod tests { use crate::{assert_needs_parentheses, assert_not_needs_parentheses}; use rome_js_syntax::{JsFileSource, JsStringLiteralExpression, ModuleKind}; #[test] fn needs_parentheses() { assert_needs_parentheses!("{ 'test'; }", JsStringLiteralExpression); assert_needs_parentheses!( r#" { console.log(5); 'test'; } "#, JsStringLiteralExpression ); assert_needs_parentheses!( r#" function Test () { ('test'); } "#, JsStringLiteralExpression ); assert_needs_parentheses!( r#" class A { static { ('test'); } } "#, JsStringLiteralExpression ); assert_needs_parentheses!( "('test');", JsStringLiteralExpression, JsFileSource::ts().with_module_kind(ModuleKind::Module) ); assert_not_needs_parentheses!("console.log('a')", JsStringLiteralExpression); } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/static_member_expression.rs
crates/rome_js_formatter/src/js/expressions/static_member_expression.rs
use crate::prelude::*; use crate::parentheses::NeedsParentheses; use crate::JsLabels; use rome_formatter::{format_args, write}; use rome_js_syntax::{ AnyJsAssignment, AnyJsAssignmentPattern, AnyJsComputedMember, AnyJsExpression, AnyJsName, JsAssignmentExpression, JsInitializerClause, JsStaticMemberAssignment, JsStaticMemberExpression, JsSyntaxKind, JsSyntaxNode, JsSyntaxToken, }; use rome_rowan::{declare_node_union, AstNode, SyntaxResult}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsStaticMemberExpression; impl FormatNodeRule<JsStaticMemberExpression> for FormatJsStaticMemberExpression { fn fmt_fields(&self, node: &JsStaticMemberExpression, f: &mut JsFormatter) -> FormatResult<()> { AnyJsStaticMemberLike::from(node.clone()).fmt(f) } fn needs_parentheses(&self, item: &JsStaticMemberExpression) -> bool { item.needs_parentheses() } } #[derive(Debug, Copy, Clone)] enum StaticMemberLikeLayout { /// Forces that there's no line break between the object, operator, and member NoBreak, /// Breaks the static member expression after the object if the whole expression doesn't fit on a single line BreakAfterObject, } declare_node_union! { pub(crate) AnyJsStaticMemberLike = JsStaticMemberExpression | JsStaticMemberAssignment } impl Format<JsFormatContext> for AnyJsStaticMemberLike { fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> { let is_member_chain = { let mut recording = f.start_recording(); write!(recording, [self.object().format()])?; recording .stop() .has_label(LabelId::of(JsLabels::MemberChain)) }; let layout = self.layout(is_member_chain)?; match layout { StaticMemberLikeLayout::NoBreak => { let format_no_break = format_with(|f| { write!(f, [self.operator_token().format(), self.member().format()]) }); if is_member_chain { write!( f, [labelled( LabelId::of(JsLabels::MemberChain), &format_no_break )] ) } else { write!(f, [format_no_break]) } } StaticMemberLikeLayout::BreakAfterObject => { write!( f, [group(&indent(&format_args![ soft_line_break(), self.operator_token().format(), self.member().format(), ]))] ) } } } } impl AnyJsStaticMemberLike { fn object(&self) -> SyntaxResult<AnyJsExpression> { match self { AnyJsStaticMemberLike::JsStaticMemberExpression(expression) => expression.object(), AnyJsStaticMemberLike::JsStaticMemberAssignment(assignment) => assignment.object(), } } fn operator_token(&self) -> SyntaxResult<JsSyntaxToken> { match self { AnyJsStaticMemberLike::JsStaticMemberExpression(expression) => { expression.operator_token() } AnyJsStaticMemberLike::JsStaticMemberAssignment(assignment) => assignment.dot_token(), } } fn member(&self) -> SyntaxResult<AnyJsName> { match self { AnyJsStaticMemberLike::JsStaticMemberExpression(expression) => expression.member(), AnyJsStaticMemberLike::JsStaticMemberAssignment(assignment) => assignment.member(), } } fn layout(&self, is_member_chain: bool) -> SyntaxResult<StaticMemberLikeLayout> { let parent = self.syntax().parent(); let object = self.object()?; let is_nested = match &parent { Some(parent) => { if JsAssignmentExpression::can_cast(parent.kind()) || JsInitializerClause::can_cast(parent.kind()) { let no_break = match &object { AnyJsExpression::JsCallExpression(call_expression) => { !call_expression.arguments()?.args().is_empty() } AnyJsExpression::TsNonNullAssertionExpression(non_null_assertion) => { match non_null_assertion.expression()? { AnyJsExpression::JsCallExpression(call_expression) => { !call_expression.arguments()?.args().is_empty() } _ => false, } } _ => false, }; if no_break || is_member_chain { return Ok(StaticMemberLikeLayout::NoBreak); } } AnyJsStaticMemberLike::can_cast(parent.kind()) || AnyJsComputedMember::can_cast(parent.kind()) } None => false, }; if !is_nested && matches!(&object, AnyJsExpression::JsIdentifierExpression(_)) { return Ok(StaticMemberLikeLayout::NoBreak); } let first_non_static_member_ancestor = self.syntax().ancestors().find(|parent| { !(AnyJsStaticMemberLike::can_cast(parent.kind()) || AnyJsComputedMember::can_cast(parent.kind())) }); let layout = match first_non_static_member_ancestor.and_then(AnyJsExpression::cast) { Some(AnyJsExpression::JsNewExpression(_)) => StaticMemberLikeLayout::NoBreak, Some(AnyJsExpression::JsAssignmentExpression(assignment)) => { if matches!( assignment.left()?, AnyJsAssignmentPattern::AnyJsAssignment( AnyJsAssignment::JsIdentifierAssignment(_) ) ) { StaticMemberLikeLayout::BreakAfterObject } else { StaticMemberLikeLayout::NoBreak } } _ => StaticMemberLikeLayout::BreakAfterObject, }; Ok(layout) } } impl NeedsParentheses for JsStaticMemberExpression { fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool { if self.is_optional_chain() && matches!(parent.kind(), JsSyntaxKind::JS_NEW_EXPRESSION) { return true; } member_chain_callee_needs_parens(self.clone().into(), parent) } } pub(crate) fn member_chain_callee_needs_parens( node: AnyJsExpression, parent: &JsSyntaxNode, ) -> bool { use AnyJsExpression::*; match parent.kind() { // `new (test().a) JsSyntaxKind::JS_NEW_EXPRESSION => { let mut object_chain = std::iter::successors(Some(node), |expression| match expression { JsStaticMemberExpression(member) => member.object().ok(), JsComputedMemberExpression(member) => member.object().ok(), JsTemplateExpression(template) => template.tag(), TsNonNullAssertionExpression(assertion) => assertion.expression().ok(), _ => None, }); object_chain.any(|object| matches!(object, JsCallExpression(_))) } _ => false, } } #[cfg(test)] mod tests { use crate::{assert_needs_parentheses, assert_not_needs_parentheses}; use rome_js_syntax::JsStaticMemberExpression; #[test] fn needs_parentheses() { assert_needs_parentheses!("new (test().a)()", JsStaticMemberExpression); assert_needs_parentheses!("new (test()[a].b)()", JsStaticMemberExpression); assert_needs_parentheses!("new (test()`template`.length)()", JsStaticMemberExpression); assert_needs_parentheses!("new (test()!.member)()", JsStaticMemberExpression); assert_needs_parentheses!("new (foo?.bar)();", JsStaticMemberExpression); assert_not_needs_parentheses!("new (test.a)()", JsStaticMemberExpression); } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/import_call_expression.rs
crates/rome_js_formatter/src/js/expressions/import_call_expression.rs
use crate::prelude::*; use crate::parentheses::NeedsParentheses; use rome_formatter::write; use rome_js_syntax::JsImportCallExpressionFields; use rome_js_syntax::{JsImportCallExpression, JsSyntaxKind, JsSyntaxNode}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsImportCallExpression; impl FormatNodeRule<JsImportCallExpression> for FormatJsImportCallExpression { fn fmt_fields(&self, node: &JsImportCallExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsImportCallExpressionFields { import_token, arguments, } = node.as_fields(); write![f, [import_token.format(), arguments.format()]] } fn needs_parentheses(&self, item: &JsImportCallExpression) -> bool { item.needs_parentheses() } } impl NeedsParentheses for JsImportCallExpression { fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool { matches!(parent.kind(), JsSyntaxKind::JS_NEW_EXPRESSION) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/post_update_expression.rs
crates/rome_js_formatter/src/js/expressions/post_update_expression.rs
use crate::prelude::*; use rome_formatter::write; use crate::parentheses::{unary_like_expression_needs_parentheses, NeedsParentheses}; use rome_js_syntax::JsPostUpdateExpressionFields; use rome_js_syntax::{JsPostUpdateExpression, JsSyntaxNode}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsPostUpdateExpression; impl FormatNodeRule<JsPostUpdateExpression> for FormatJsPostUpdateExpression { fn fmt_fields(&self, node: &JsPostUpdateExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsPostUpdateExpressionFields { operand, operator_token, } = node.as_fields(); write![f, [operand.format(), operator_token.format()]] } fn needs_parentheses(&self, item: &JsPostUpdateExpression) -> bool { item.needs_parentheses() } } impl NeedsParentheses for JsPostUpdateExpression { fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool { unary_like_expression_needs_parentheses(self.syntax(), parent) } } #[cfg(test)] mod tests { use crate::{assert_needs_parentheses, assert_not_needs_parentheses}; use rome_js_syntax::JsPostUpdateExpression; #[test] fn needs_parentheses() { assert_needs_parentheses!("class A extends (A++) {}", JsPostUpdateExpression); assert_needs_parentheses!("(a++).b", JsPostUpdateExpression); assert_needs_parentheses!("(a++)[b]", JsPostUpdateExpression); assert_not_needs_parentheses!("a[b++]", JsPostUpdateExpression); assert_needs_parentheses!("(a++)`template`", JsPostUpdateExpression); assert_needs_parentheses!("(a++)()", JsPostUpdateExpression); assert_needs_parentheses!("new (a++)()", JsPostUpdateExpression); assert_needs_parentheses!("(a++)!", JsPostUpdateExpression); assert_needs_parentheses!("(a++) ** 3", JsPostUpdateExpression); assert_not_needs_parentheses!("(a++) + 3", JsPostUpdateExpression); } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/parenthesized_expression.rs
crates/rome_js_formatter/src/js/expressions/parenthesized_expression.rs
use crate::prelude::*; use rome_formatter::{format_args, write, CstFormatContext}; use crate::parentheses::NeedsParentheses; use rome_js_syntax::{ AnyJsExpression, JsParenthesizedExpression, JsParenthesizedExpressionFields, JsSyntaxNode, }; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsParenthesizedExpression; impl FormatNodeRule<JsParenthesizedExpression> for FormatJsParenthesizedExpression { fn fmt_fields( &self, node: &JsParenthesizedExpression, f: &mut JsFormatter, ) -> FormatResult<()> { let JsParenthesizedExpressionFields { l_paren_token, expression, r_paren_token, } = node.as_fields(); let l_paren_token = l_paren_token?; let expression = expression?; let comments = f.context().comments(); let should_hug = !comments.has_comments(expression.syntax()) && (matches!( expression, AnyJsExpression::JsObjectExpression(_) | AnyJsExpression::JsArrayExpression(_) )); if should_hug { write!( f, [ l_paren_token.format(), expression.format(), r_paren_token.format() ] ) } else { write!( f, [group(&format_args![ l_paren_token.format(), soft_block_indent(&expression.format()), r_paren_token.format() ])] ) } } fn needs_parentheses(&self, item: &JsParenthesizedExpression) -> bool { item.needs_parentheses() } } impl NeedsParentheses for JsParenthesizedExpression { #[inline(always)] fn needs_parentheses(&self) -> bool { false } #[inline(always)] fn needs_parentheses_with_parent(&self, _parent: &JsSyntaxNode) -> bool { false } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/pre_update_expression.rs
crates/rome_js_formatter/src/js/expressions/pre_update_expression.rs
use crate::parentheses::{unary_like_expression_needs_parentheses, NeedsParentheses}; use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::JsPreUpdateExpressionFields; use rome_js_syntax::{ JsPreUpdateExpression, JsPreUpdateOperator, JsSyntaxNode, JsUnaryExpression, JsUnaryOperator, }; use rome_rowan::match_ast; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsPreUpdateExpression; impl FormatNodeRule<JsPreUpdateExpression> for FormatJsPreUpdateExpression { fn fmt_fields(&self, node: &JsPreUpdateExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsPreUpdateExpressionFields { operator_token, operand, } = node.as_fields(); write![f, [operator_token.format(), operand.format(),]] } fn needs_parentheses(&self, item: &JsPreUpdateExpression) -> bool { item.needs_parentheses() } } impl NeedsParentheses for JsPreUpdateExpression { fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool { match_ast! { match parent { JsUnaryExpression(unary) => { let parent_operator = unary.operator(); let operator = self.operator(); (parent_operator == Ok(JsUnaryOperator::Plus) && operator == Ok(JsPreUpdateOperator::Increment)) || (parent_operator == Ok(JsUnaryOperator::Minus) && operator == Ok(JsPreUpdateOperator::Decrement)) }, _ => { unary_like_expression_needs_parentheses(self.syntax(), parent) } } } } } #[cfg(test)] mod tests { use crate::{assert_needs_parentheses, assert_not_needs_parentheses}; use rome_js_syntax::JsPreUpdateExpression; #[test] fn needs_parentheses() { // valid, but should become +(++a) assert_needs_parentheses!("+ ++a", JsPreUpdateExpression); assert_needs_parentheses!("class A extends (++A) {}", JsPreUpdateExpression); assert_needs_parentheses!("(++a).b", JsPreUpdateExpression); assert_needs_parentheses!("(++a)[b]", JsPreUpdateExpression); assert_not_needs_parentheses!("a[++b]", JsPreUpdateExpression); assert_needs_parentheses!("(++a)`template`", JsPreUpdateExpression); assert_needs_parentheses!("(++a)()", JsPreUpdateExpression); assert_needs_parentheses!("new (++a)()", JsPreUpdateExpression); assert_needs_parentheses!("(++a)!", JsPreUpdateExpression); assert_needs_parentheses!("(++a) ** 3", JsPreUpdateExpression); assert_not_needs_parentheses!("(++a) + 3", JsPreUpdateExpression); } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/class_expression.rs
crates/rome_js_formatter/src/js/expressions/class_expression.rs
use crate::prelude::*; use crate::utils::format_class::FormatClass; use rome_formatter::{format_args, write}; use crate::parentheses::{ is_callee, is_first_in_statement, FirstInStatementMode, NeedsParentheses, }; use rome_js_syntax::{JsClassExpression, JsSyntaxNode}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsClassExpression; impl FormatNodeRule<JsClassExpression> for FormatJsClassExpression { fn fmt_fields(&self, node: &JsClassExpression, f: &mut JsFormatter) -> FormatResult<()> { if node.decorators().is_empty() { FormatClass::from(&node.clone().into()).fmt(f) } else { write!( f, [ indent(&format_args![ soft_line_break_or_space(), &FormatClass::from(&node.clone().into()), ]), soft_line_break_or_space() ] ) } } fn needs_parentheses(&self, item: &JsClassExpression) -> bool { !item.decorators().is_empty() || item.needs_parentheses() } fn fmt_dangling_comments( &self, _: &JsClassExpression, _: &mut JsFormatter, ) -> FormatResult<()> { // Formatted as part of `FormatClass` Ok(()) } } impl NeedsParentheses for JsClassExpression { fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool { is_callee(self.syntax(), parent) || is_first_in_statement( self.clone().into(), FirstInStatementMode::ExpressionOrExportDefault, ) } } #[cfg(test)] mod tests { use crate::{assert_needs_parentheses, assert_not_needs_parentheses}; use rome_js_syntax::JsClassExpression; #[test] fn needs_parentheses() { assert_needs_parentheses!("console.log((class {})())", JsClassExpression); assert_needs_parentheses!("console.log(new (class {})())", JsClassExpression); assert_needs_parentheses!("(class {}).test", JsClassExpression); assert_not_needs_parentheses!("a => class {} ", JsClassExpression); assert_needs_parentheses!("export default (class {})", JsClassExpression); } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/in_expression.rs
crates/rome_js_formatter/src/js/expressions/in_expression.rs
use crate::prelude::*; use crate::utils::{needs_binary_like_parentheses, AnyJsBinaryLikeExpression}; use crate::parentheses::NeedsParentheses; use rome_js_syntax::{AnyJsStatement, JsForStatement, JsInExpression, JsSyntaxNode}; use rome_rowan::AstNode; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsInExpression; impl FormatNodeRule<JsInExpression> for FormatJsInExpression { fn fmt_fields(&self, node: &JsInExpression, formatter: &mut JsFormatter) -> FormatResult<()> { AnyJsBinaryLikeExpression::JsInExpression(node.clone()).fmt(formatter) } fn needs_parentheses(&self, item: &JsInExpression) -> bool { item.needs_parentheses() } } impl NeedsParentheses for JsInExpression { fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool { if is_in_for_initializer(self) { return true; } needs_binary_like_parentheses(&AnyJsBinaryLikeExpression::from(self.clone()), parent) } } /// Add parentheses if the `in` is inside of a `for` initializer (see tests). fn is_in_for_initializer(expression: &JsInExpression) -> bool { let mut current = expression.clone().into_syntax(); while let Some(parent) = current.parent() { current = match JsForStatement::try_cast(parent) { Ok(for_statement) => { return for_statement .initializer() .map(AstNode::into_syntax) .as_ref() == Some(&current); } Err(parent) => { if AnyJsStatement::can_cast(parent.kind()) { // Don't cross statement boundaries break; } parent } } } false } #[cfg(test)] mod tests { use crate::{assert_needs_parentheses, assert_not_needs_parentheses}; use rome_js_syntax::{JsFileSource, JsInExpression}; #[test] fn needs_parentheses() { assert_needs_parentheses!("class X extends (a in b) {}", JsInExpression); assert_needs_parentheses!("(a in b) as number", JsInExpression); assert_needs_parentheses!("<number>(a in b)", JsInExpression); assert_needs_parentheses!("!(a in b)", JsInExpression); assert_needs_parentheses!("await (a in b)", JsInExpression); assert_needs_parentheses!("(a in b)!", JsInExpression); assert_needs_parentheses!("(a in b)()", JsInExpression); assert_needs_parentheses!("(a in b)?.()", JsInExpression); assert_needs_parentheses!("new (a in b)()", JsInExpression); assert_needs_parentheses!("(a in b)`template`", JsInExpression); assert_needs_parentheses!("[...(a in b)]", JsInExpression); assert_needs_parentheses!("({...(a in b)})", JsInExpression); assert_needs_parentheses!( "<test {...(a in b)} />", JsInExpression, JsFileSource::tsx() ); assert_needs_parentheses!( "<test>{...(a in b)}</test>", JsInExpression, JsFileSource::tsx() ); assert_needs_parentheses!("(a in b).member", JsInExpression); assert_needs_parentheses!("(a in b)[member]", JsInExpression); assert_not_needs_parentheses!("object[a in b]", JsInExpression); assert_needs_parentheses!("(a in b) + c", JsInExpression); assert_not_needs_parentheses!("a in b > c", JsInExpression); assert_not_needs_parentheses!("a in b instanceof C", JsInExpression); assert_not_needs_parentheses!("a in b in c", JsInExpression[0]); assert_not_needs_parentheses!("a in b in c", JsInExpression[1]); } #[test] fn for_in_needs_parentheses() { assert_needs_parentheses!("for (let a = (b in c);;);", JsInExpression); assert_needs_parentheses!("for (a && (b in c);;);", JsInExpression); assert_needs_parentheses!("for (a => (b in c);;);", JsInExpression); assert_needs_parentheses!( "function* g() { for (yield (a in b);;); }", JsInExpression ); assert_needs_parentheses!( "async function f() { for (await (a in b);;); }", JsInExpression ); assert_not_needs_parentheses!("for (;a in b;);", JsInExpression); assert_not_needs_parentheses!("for (;;a in b);", JsInExpression); assert_not_needs_parentheses!( r#" for (function () { a in b }();;); "#, JsInExpression ); } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/array_expression.rs
crates/rome_js_formatter/src/js/expressions/array_expression.rs
use crate::prelude::*; use crate::parentheses::NeedsParentheses; use rome_formatter::{write, FormatRuleWithOptions}; use rome_js_syntax::{ AnyJsArrayElement, AnyJsExpression, JsArrayElementList, JsArrayExpressionFields, }; use rome_js_syntax::{JsArrayExpression, JsSyntaxNode}; use rome_rowan::SyntaxResult; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsArrayExpression { options: FormatJsArrayExpressionOptions, } impl FormatRuleWithOptions<JsArrayExpression> for FormatJsArrayExpression { type Options = FormatJsArrayExpressionOptions; fn with_options(mut self, options: Self::Options) -> Self { self.options = options; self } } impl FormatNodeRule<JsArrayExpression> for FormatJsArrayExpression { fn fmt_fields(&self, node: &JsArrayExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsArrayExpressionFields { l_brack_token, elements, r_brack_token, } = node.as_fields(); let r_brack_token = r_brack_token?; if elements.is_empty() { write!( f, [ l_brack_token.format(), format_dangling_comments(node.syntax()).with_block_indent(), r_brack_token.format(), ] ) } else { let group_id = f.group_id("array"); let should_expand = !self.options.is_force_flat_mode && should_break(&elements)?; let elements = elements.format().with_options(Some(group_id)); write!( f, [ l_brack_token.format(), group(&soft_block_indent(&elements)) .with_group_id(Some(group_id)) .should_expand(should_expand), r_brack_token.format() ] ) } } fn needs_parentheses(&self, item: &JsArrayExpression) -> bool { item.needs_parentheses() } fn fmt_dangling_comments( &self, _: &JsArrayExpression, _: &mut JsFormatter, ) -> FormatResult<()> { // Formatted inside of `fmt_fields` Ok(()) } } #[derive(Debug, Copy, Clone, Default)] pub(crate) struct FormatJsArrayExpressionOptions { pub(crate) is_force_flat_mode: bool, } /// Returns `true` for arrays containing at least two elements if: /// * all elements are either object or array expressions /// * each child array expression has at least two elements, or each child object expression has at least two members. fn should_break(elements: &JsArrayElementList) -> SyntaxResult<bool> { if elements.len() < 2 { Ok(false) } else { let mut elements = elements.iter().peekable(); while let Some(element) = elements.next() { match element? { AnyJsArrayElement::AnyJsExpression(AnyJsExpression::JsArrayExpression(array)) => { let next_is_array_or_end = matches!( elements.peek(), None | Some(Ok(AnyJsArrayElement::AnyJsExpression( AnyJsExpression::JsArrayExpression(_) ))) ); if array.elements().len() < 2 || !next_is_array_or_end { return Ok(false); } } AnyJsArrayElement::AnyJsExpression(AnyJsExpression::JsObjectExpression(object)) => { let next_is_object_or_empty = matches!( elements.peek(), None | Some(Ok(AnyJsArrayElement::AnyJsExpression( AnyJsExpression::JsObjectExpression(_) ))) ); if object.members().len() < 2 || !next_is_object_or_empty { return Ok(false); } } _ => { return Ok(false); } } } Ok(true) } } impl NeedsParentheses for JsArrayExpression { #[inline(always)] fn needs_parentheses(&self) -> bool { false } #[inline(always)] fn needs_parentheses_with_parent(&self, _parent: &JsSyntaxNode) -> bool { false } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/new_expression.rs
crates/rome_js_formatter/src/js/expressions/new_expression.rs
use crate::prelude::*; use crate::parentheses::NeedsParentheses; use rome_formatter::write; use rome_js_syntax::{JsNewExpression, JsSyntaxKind}; use rome_js_syntax::{JsNewExpressionFields, JsSyntaxNode}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsNewExpression; impl FormatNodeRule<JsNewExpression> for FormatJsNewExpression { fn fmt_fields(&self, node: &JsNewExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsNewExpressionFields { new_token, callee, type_arguments, arguments, } = node.as_fields(); write![ f, [ new_token.format(), space(), callee.format(), type_arguments.format(), ] ]?; match arguments { Some(arguments) => { write!(f, [arguments.format()]) } None => { write!(f, [text("("), text(")")]) } } } fn needs_parentheses(&self, item: &JsNewExpression) -> bool { item.needs_parentheses() } } impl NeedsParentheses for JsNewExpression { fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool { matches!(parent.kind(), JsSyntaxKind::JS_EXTENDS_CLAUSE) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/instanceof_expression.rs
crates/rome_js_formatter/src/js/expressions/instanceof_expression.rs
use crate::prelude::*; use crate::utils::{needs_binary_like_parentheses, AnyJsBinaryLikeExpression}; use crate::parentheses::NeedsParentheses; use rome_js_syntax::{JsInstanceofExpression, JsSyntaxNode}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsInstanceofExpression; impl FormatNodeRule<JsInstanceofExpression> for FormatJsInstanceofExpression { fn fmt_fields( &self, node: &JsInstanceofExpression, formatter: &mut JsFormatter, ) -> FormatResult<()> { AnyJsBinaryLikeExpression::JsInstanceofExpression(node.clone()).fmt(formatter) } fn needs_parentheses(&self, item: &JsInstanceofExpression) -> bool { item.needs_parentheses() } } impl NeedsParentheses for JsInstanceofExpression { fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool { needs_binary_like_parentheses(&AnyJsBinaryLikeExpression::from(self.clone()), parent) } } #[cfg(test)] mod tests { use crate::{assert_needs_parentheses, assert_not_needs_parentheses}; use rome_js_syntax::{JsFileSource, JsInstanceofExpression}; #[test] fn needs_parentheses() { assert_needs_parentheses!( "class X extends (a instanceof b) {}", JsInstanceofExpression ); assert_needs_parentheses!("(a instanceof B) as number", JsInstanceofExpression); assert_needs_parentheses!("<number>(a instanceof B)", JsInstanceofExpression); assert_needs_parentheses!("!(a instanceof B)", JsInstanceofExpression); assert_needs_parentheses!("await (a instanceof B)", JsInstanceofExpression); assert_needs_parentheses!("(a instanceof B)!", JsInstanceofExpression); assert_needs_parentheses!("(a instanceof B)()", JsInstanceofExpression); assert_needs_parentheses!("(a instanceof B)?.()", JsInstanceofExpression); assert_needs_parentheses!("new (a instanceof B)()", JsInstanceofExpression); assert_needs_parentheses!("(a instanceof B)`template`", JsInstanceofExpression); assert_needs_parentheses!("[...(a instanceof B)]", JsInstanceofExpression); assert_needs_parentheses!("({...(a instanceof B)})", JsInstanceofExpression); assert_needs_parentheses!( "<test {...(a instanceof B)} />", JsInstanceofExpression, JsFileSource::tsx() ); assert_needs_parentheses!( "<test>{...(a instanceof B)}</test>", JsInstanceofExpression, JsFileSource::tsx() ); assert_needs_parentheses!("(a instanceof B).member", JsInstanceofExpression); assert_needs_parentheses!("(a instanceof B)[member]", JsInstanceofExpression); assert_not_needs_parentheses!("object[a instanceof B]", JsInstanceofExpression); assert_needs_parentheses!("(a instanceof B) + c", JsInstanceofExpression); assert_not_needs_parentheses!("a instanceof B > c", JsInstanceofExpression); assert_not_needs_parentheses!("a instanceof B in c", JsInstanceofExpression); assert_not_needs_parentheses!("a instanceof B instanceof c", JsInstanceofExpression[0]); assert_not_needs_parentheses!("a instanceof B instanceof c", JsInstanceofExpression[1]); } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/null_literal_expression.rs
crates/rome_js_formatter/src/js/expressions/null_literal_expression.rs
use crate::prelude::*; use crate::parentheses::NeedsParentheses; use rome_formatter::write; use rome_js_syntax::JsNullLiteralExpressionFields; use rome_js_syntax::{JsNullLiteralExpression, JsSyntaxNode}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsNullLiteralExpression; impl FormatNodeRule<JsNullLiteralExpression> for FormatJsNullLiteralExpression { fn fmt_fields(&self, node: &JsNullLiteralExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsNullLiteralExpressionFields { value_token } = node.as_fields(); write![f, [value_token.format()]] } fn needs_parentheses(&self, item: &JsNullLiteralExpression) -> bool { item.needs_parentheses() } } impl NeedsParentheses for JsNullLiteralExpression { #[inline(always)] fn needs_parentheses(&self) -> bool { false } #[inline(always)] fn needs_parentheses_with_parent(&self, _parent: &JsSyntaxNode) -> bool { false } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/object_expression.rs
crates/rome_js_formatter/src/js/expressions/object_expression.rs
use crate::parentheses::{is_first_in_statement, FirstInStatementMode, NeedsParentheses}; use crate::prelude::*; use crate::utils::JsObjectLike; use rome_formatter::write; use rome_js_syntax::{JsObjectExpression, JsSyntaxKind, JsSyntaxNode}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsObjectExpression; impl FormatNodeRule<JsObjectExpression> for FormatJsObjectExpression { fn fmt_fields(&self, node: &JsObjectExpression, f: &mut JsFormatter) -> FormatResult<()> { write!(f, [JsObjectLike::from(node.clone())]) } fn needs_parentheses(&self, item: &JsObjectExpression) -> bool { item.needs_parentheses() } fn fmt_dangling_comments( &self, _: &JsObjectExpression, _: &mut JsFormatter, ) -> FormatResult<()> { // Formatted inside of `JsObjectLike` Ok(()) } } impl NeedsParentheses for JsObjectExpression { fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool { matches!(parent.kind(), JsSyntaxKind::JS_EXTENDS_CLAUSE) || is_first_in_statement( self.clone().into(), FirstInStatementMode::ExpressionStatementOrArrow, ) } } #[cfg(test)] mod tests { use crate::assert_needs_parentheses; use rome_js_syntax::JsObjectExpression; #[test] fn needs_parentheses() { assert_needs_parentheses!("class A extends ({}) {}", JsObjectExpression); assert_needs_parentheses!("({a: 5})", JsObjectExpression); assert_needs_parentheses!("a => ({ a: 5})", JsObjectExpression); assert_needs_parentheses!("a => ({ a: 'test' })`template`", JsObjectExpression); assert_needs_parentheses!("({ a: 'test' }).member", JsObjectExpression); assert_needs_parentheses!("({ a: 'test' })[member]", JsObjectExpression); assert_needs_parentheses!("({ a: 'test' })()", JsObjectExpression); assert_needs_parentheses!("new ({ a: 'test' })()", JsObjectExpression); assert_needs_parentheses!("({ a: 'test' }) as number", JsObjectExpression); assert_needs_parentheses!("({ a: 'test' })!", JsObjectExpression); assert_needs_parentheses!("({ a: 'test' }), b, c", JsObjectExpression); assert_needs_parentheses!("({ a: 'test' }) + 5", JsObjectExpression); assert_needs_parentheses!("({ a: 'test' }) && true", JsObjectExpression); assert_needs_parentheses!("({ a: 'test' }) instanceof A", JsObjectExpression); assert_needs_parentheses!("({ a: 'test' }) in B", JsObjectExpression); } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/mod.rs
crates/rome_js_formatter/src/js/expressions/mod.rs
//! This is a generated file. Don't modify it by hand! Run 'cargo codegen formatter' to re-generate the file. pub(crate) mod array_expression; pub(crate) mod arrow_function_expression; pub(crate) mod assignment_expression; pub(crate) mod await_expression; pub(crate) mod bigint_literal_expression; pub(crate) mod binary_expression; pub(crate) mod boolean_literal_expression; pub(crate) mod call_arguments; pub(crate) mod call_expression; pub(crate) mod class_expression; pub(crate) mod computed_member_expression; pub(crate) mod conditional_expression; pub(crate) mod function_expression; pub(crate) mod identifier_expression; pub(crate) mod import_call_expression; pub(crate) mod import_meta_expression; pub(crate) mod in_expression; pub(crate) mod instanceof_expression; pub(crate) mod logical_expression; pub(crate) mod new_expression; pub(crate) mod new_target_expression; pub(crate) mod null_literal_expression; pub(crate) mod number_literal_expression; pub(crate) mod object_expression; pub(crate) mod parenthesized_expression; pub(crate) mod post_update_expression; pub(crate) mod pre_update_expression; pub(crate) mod regex_literal_expression; pub(crate) mod sequence_expression; pub(crate) mod static_member_expression; pub(crate) mod string_literal_expression; pub(crate) mod super_expression; pub(crate) mod template_expression; pub(crate) mod this_expression; pub(crate) mod unary_expression; pub(crate) mod yield_argument; pub(crate) mod yield_expression;
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/computed_member_expression.rs
crates/rome_js_formatter/src/js/expressions/computed_member_expression.rs
use crate::prelude::*; use crate::js::expressions::static_member_expression::member_chain_callee_needs_parens; use crate::parentheses::NeedsParentheses; use rome_formatter::{format_args, write}; use rome_js_syntax::{ AnyJsComputedMember, AnyJsExpression, AnyJsLiteralExpression, JsComputedMemberExpression, JsSyntaxKind, JsSyntaxNode, }; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsComputedMemberExpression; impl FormatNodeRule<JsComputedMemberExpression> for FormatJsComputedMemberExpression { fn fmt_fields( &self, node: &JsComputedMemberExpression, f: &mut JsFormatter, ) -> FormatResult<()> { AnyJsComputedMember::from(node.clone()).fmt(f) } fn needs_parentheses(&self, item: &JsComputedMemberExpression) -> bool { item.needs_parentheses() } } impl Format<JsFormatContext> for AnyJsComputedMember { fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> { write!(f, [self.object().format()])?; FormatComputedMemberLookup(self).fmt(f) } } /// Formats the lookup portion (everything except the object) of a computed member like. pub(crate) struct FormatComputedMemberLookup<'a>(&'a AnyJsComputedMember); impl<'a> FormatComputedMemberLookup<'a> { pub(crate) fn new(member_like: &'a AnyJsComputedMember) -> Self { Self(member_like) } } impl Format<JsFormatContext> for FormatComputedMemberLookup<'_> { fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> { match self.0.member()? { AnyJsExpression::AnyJsLiteralExpression( AnyJsLiteralExpression::JsNumberLiteralExpression(literal), ) => { write!( f, [ self.0.optional_chain_token().format(), self.0.l_brack_token().format(), literal.format(), self.0.r_brack_token().format() ] ) } member => { write![ f, [group(&format_args![ self.0.optional_chain_token().format(), self.0.l_brack_token().format(), soft_block_indent(&member.format()), self.0.r_brack_token().format() ])] ] } } } } impl NeedsParentheses for JsComputedMemberExpression { fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool { if self.is_optional_chain() && matches!(parent.kind(), JsSyntaxKind::JS_NEW_EXPRESSION) { return true; } member_chain_callee_needs_parens(self.clone().into(), parent) } } #[cfg(test)] mod tests { use crate::{assert_needs_parentheses, assert_not_needs_parentheses}; use rome_js_syntax::JsComputedMemberExpression; #[test] fn needs_parentheses() { assert_needs_parentheses!("new (test()[a])()", JsComputedMemberExpression); assert_needs_parentheses!("new (test().a[b])()", JsComputedMemberExpression); assert_needs_parentheses!( "new (test()`template`[index])()", JsComputedMemberExpression ); assert_needs_parentheses!("new (test()![member])()", JsComputedMemberExpression); assert_needs_parentheses!("new (a?.b[c])()", JsComputedMemberExpression); assert_not_needs_parentheses!("new (test[a])()", JsComputedMemberExpression); } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/call_expression.rs
crates/rome_js_formatter/src/js/expressions/call_expression.rs
use crate::prelude::*; use rome_formatter::write; use crate::parentheses::NeedsParentheses; use crate::utils::member_chain::MemberChain; use rome_js_syntax::{ AnyJsExpression, JsCallExpression, JsCallExpressionFields, JsSyntaxKind, JsSyntaxNode, }; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsCallExpression; impl FormatNodeRule<JsCallExpression> for FormatJsCallExpression { fn fmt_fields(&self, node: &JsCallExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsCallExpressionFields { callee, optional_chain_token, type_arguments, arguments, } = node.as_fields(); let callee = callee?; if matches!( callee, AnyJsExpression::JsStaticMemberExpression(_) | AnyJsExpression::JsComputedMemberExpression(_) ) && !callee.needs_parentheses() { let member_chain = MemberChain::from_call_expression( node.clone(), f.comments(), f.options().tab_width(), )?; member_chain.fmt(f) } else { let format_inner = format_with(|f| { write!( f, [ callee.format(), optional_chain_token.format(), type_arguments.format(), arguments.format() ] ) }); if matches!(callee, AnyJsExpression::JsCallExpression(_)) { write!(f, [group(&format_inner)]) } else { write!(f, [format_inner]) } } } fn needs_parentheses(&self, item: &JsCallExpression) -> bool { item.needs_parentheses() } } impl NeedsParentheses for JsCallExpression { fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool { matches!(parent.kind(), JsSyntaxKind::JS_NEW_EXPRESSION) } } #[cfg(test)] mod tests { use crate::{assert_needs_parentheses, assert_not_needs_parentheses}; use rome_js_syntax::JsCallExpression; #[test] fn needs_parentheses() { assert_needs_parentheses!("new (call())()", JsCallExpression); assert_not_needs_parentheses!("a?.()!.c", JsCallExpression); assert_not_needs_parentheses!("(a?.())!.c", JsCallExpression); assert_not_needs_parentheses!("(call())()", JsCallExpression[1]); assert_not_needs_parentheses!("getLogger().error(err);", JsCallExpression[0]); assert_not_needs_parentheses!("getLogger().error(err);", JsCallExpression[1]); } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/await_expression.rs
crates/rome_js_formatter/src/js/expressions/await_expression.rs
use crate::prelude::*; use rome_formatter::write; use crate::parentheses::{ is_binary_like_left_or_right, is_callee, is_conditional_test, is_member_object, is_spread, update_or_lower_expression_needs_parentheses, NeedsParentheses, }; use rome_js_syntax::{JsAwaitExpression, JsSyntaxNode}; use rome_js_syntax::{JsAwaitExpressionFields, JsSyntaxKind}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsAwaitExpression; impl FormatNodeRule<JsAwaitExpression> for FormatJsAwaitExpression { fn fmt_fields(&self, node: &JsAwaitExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsAwaitExpressionFields { await_token, argument, } = node.as_fields(); let format_inner = format_with(|f| write![f, [await_token.format(), space(), argument.format()]]); let parent = node.syntax().parent(); if let Some(parent) = parent { if is_callee(node.syntax(), &parent) || is_member_object(node.syntax(), &parent) { let ancestor_await_or_block = parent.ancestors().skip(1).find(|ancestor| { matches!( ancestor.kind(), JsSyntaxKind::JS_AWAIT_EXPRESSION // Stop at statement boundaries. | JsSyntaxKind::JS_STATEMENT_LIST | JsSyntaxKind::JS_MODULE_ITEM_LIST ) }); let indented = format_with(|f| write!(f, [soft_block_indent(&format_inner)])); return if ancestor_await_or_block.map_or(false, |ancestor| { JsAwaitExpression::can_cast(ancestor.kind()) }) { write!(f, [indented]) } else { write!(f, [group(&indented)]) }; } } write!(f, [format_inner]) } fn needs_parentheses(&self, item: &JsAwaitExpression) -> bool { item.needs_parentheses() } } impl NeedsParentheses for JsAwaitExpression { fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool { await_or_yield_needs_parens(parent, self.syntax()) } } pub(super) fn await_or_yield_needs_parens(parent: &JsSyntaxNode, node: &JsSyntaxNode) -> bool { debug_assert!(matches!( node.kind(), JsSyntaxKind::JS_AWAIT_EXPRESSION | JsSyntaxKind::JS_YIELD_EXPRESSION )); match parent.kind() { JsSyntaxKind::JS_UNARY_EXPRESSION | JsSyntaxKind::TS_AS_EXPRESSION | JsSyntaxKind::TS_SATISFIES_EXPRESSION => true, _ => { let expression = node; is_conditional_test(node, parent) || update_or_lower_expression_needs_parentheses(expression, parent) || is_spread(expression, parent) || is_binary_like_left_or_right(node, parent) } } } #[cfg(test)] mod tests { use crate::{assert_needs_parentheses, assert_not_needs_parentheses}; use rome_js_syntax::JsAwaitExpression; #[test] fn needs_parentheses() { assert_needs_parentheses!("(await a)`template`", JsAwaitExpression); assert_needs_parentheses!("+(await a)", JsAwaitExpression); assert_needs_parentheses!("(await a).b", JsAwaitExpression); assert_needs_parentheses!("(await a)[b]", JsAwaitExpression); assert_not_needs_parentheses!("a[await b]", JsAwaitExpression); assert_needs_parentheses!("(await a)()", JsAwaitExpression); assert_needs_parentheses!("new (await a)()", JsAwaitExpression); assert_needs_parentheses!("(await a) && b", JsAwaitExpression); assert_needs_parentheses!("(await a) + b", JsAwaitExpression); assert_needs_parentheses!("(await a) instanceof b", JsAwaitExpression); assert_needs_parentheses!("(await a) in b", JsAwaitExpression); assert_needs_parentheses!("[...(await a)]", JsAwaitExpression); assert_needs_parentheses!("({...(await b)})", JsAwaitExpression); assert_needs_parentheses!("call(...(await b))", JsAwaitExpression); assert_needs_parentheses!("class A extends (await b) {}", JsAwaitExpression); assert_needs_parentheses!("(await b) as number", JsAwaitExpression); assert_needs_parentheses!("(await b)!", JsAwaitExpression); assert_needs_parentheses!("(await b) ? b : c", JsAwaitExpression); assert_not_needs_parentheses!("a ? await b : c", JsAwaitExpression); assert_not_needs_parentheses!("a ? b : await c", JsAwaitExpression); } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/identifier_expression.rs
crates/rome_js_formatter/src/js/expressions/identifier_expression.rs
use crate::prelude::*; use crate::parentheses::NeedsParentheses; use rome_formatter::write; use rome_js_syntax::JsIdentifierExpressionFields; use rome_js_syntax::{JsIdentifierExpression, JsSyntaxNode}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsIdentifierExpression; impl FormatNodeRule<JsIdentifierExpression> for FormatJsIdentifierExpression { fn fmt_fields(&self, node: &JsIdentifierExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsIdentifierExpressionFields { name } = node.as_fields(); write![f, [name.format()]] } fn needs_parentheses(&self, item: &JsIdentifierExpression) -> bool { item.needs_parentheses() } } impl NeedsParentheses for JsIdentifierExpression { #[inline(always)] fn needs_parentheses(&self) -> bool { false } #[inline(always)] fn needs_parentheses_with_parent(&self, _parent: &JsSyntaxNode) -> bool { false } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/number_literal_expression.rs
crates/rome_js_formatter/src/js/expressions/number_literal_expression.rs
use crate::prelude::*; use rome_formatter::token::number::format_number_token; use crate::parentheses::{is_member_object, NeedsParentheses}; use rome_js_syntax::JsNumberLiteralExpression; use rome_js_syntax::{JsNumberLiteralExpressionFields, JsSyntaxNode}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsNumberLiteralExpression; impl FormatNodeRule<JsNumberLiteralExpression> for FormatJsNumberLiteralExpression { fn fmt_fields( &self, node: &JsNumberLiteralExpression, f: &mut JsFormatter, ) -> FormatResult<()> { let JsNumberLiteralExpressionFields { value_token } = node.as_fields(); format_number_token(&value_token?).fmt(f) } fn needs_parentheses(&self, item: &JsNumberLiteralExpression) -> bool { item.needs_parentheses() } } impl NeedsParentheses for JsNumberLiteralExpression { fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool { is_member_object(self.syntax(), parent) } } #[cfg(test)] mod tests { use crate::{assert_needs_parentheses, assert_not_needs_parentheses}; use rome_js_syntax::JsNumberLiteralExpression; #[test] fn needs_parentheses() { assert_needs_parentheses!("(5).test", JsNumberLiteralExpression); assert_needs_parentheses!("(5)[test]", JsNumberLiteralExpression); assert_not_needs_parentheses!("test[5]", JsNumberLiteralExpression); } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/logical_expression.rs
crates/rome_js_formatter/src/js/expressions/logical_expression.rs
use crate::prelude::*; use crate::utils::{needs_binary_like_parentheses, AnyJsBinaryLikeExpression}; use crate::parentheses::NeedsParentheses; use rome_js_syntax::{JsLogicalExpression, JsSyntaxNode}; use rome_rowan::AstNode; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsLogicalExpression; impl FormatNodeRule<JsLogicalExpression> for FormatJsLogicalExpression { fn fmt_fields( &self, node: &JsLogicalExpression, formatter: &mut JsFormatter, ) -> FormatResult<()> { AnyJsBinaryLikeExpression::JsLogicalExpression(node.clone()).fmt(formatter) } fn needs_parentheses(&self, item: &JsLogicalExpression) -> bool { item.needs_parentheses() } } impl NeedsParentheses for JsLogicalExpression { fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool { if let Some(parent) = JsLogicalExpression::cast(parent.clone()) { parent.operator() != self.operator() } else { needs_binary_like_parentheses(&AnyJsBinaryLikeExpression::from(self.clone()), parent) } } } #[cfg(test)] mod tests { use crate::{assert_needs_parentheses, assert_not_needs_parentheses}; use rome_js_syntax::{JsFileSource, JsLogicalExpression}; #[test] fn needs_parentheses() { assert_needs_parentheses!("class X extends (a && b) {}", JsLogicalExpression); assert_needs_parentheses!("(a && b) as number", JsLogicalExpression); assert_needs_parentheses!("<number>(a && b)", JsLogicalExpression); assert_needs_parentheses!("!(a && b)", JsLogicalExpression); assert_needs_parentheses!("await (a && b)", JsLogicalExpression); assert_needs_parentheses!("(a && b)!", JsLogicalExpression); assert_needs_parentheses!("(a && b)()", JsLogicalExpression); assert_needs_parentheses!("(a && b)?.()", JsLogicalExpression); assert_needs_parentheses!("new (a && b)()", JsLogicalExpression); assert_needs_parentheses!("(a && b)`template`", JsLogicalExpression); assert_needs_parentheses!("[...(a && b)]", JsLogicalExpression); assert_needs_parentheses!("({...(a && b)})", JsLogicalExpression); assert_needs_parentheses!( "<test {...(a && b)} />", JsLogicalExpression, JsFileSource::tsx() ); assert_needs_parentheses!( "<test>{...(a && b)}</test>", JsLogicalExpression, JsFileSource::tsx() ); assert_needs_parentheses!("(a && b).member", JsLogicalExpression); assert_needs_parentheses!("(a && b)[member]", JsLogicalExpression); assert_not_needs_parentheses!("object[a && b]", JsLogicalExpression); assert_needs_parentheses!("(a && b) || c", JsLogicalExpression[1]); assert_needs_parentheses!("(a && b) in c", JsLogicalExpression); assert_needs_parentheses!("(a && b) instanceof c", JsLogicalExpression); assert_needs_parentheses!("(a && b) + c", JsLogicalExpression); assert_not_needs_parentheses!("a && b && c", JsLogicalExpression[0]); assert_not_needs_parentheses!("a && b && c", JsLogicalExpression[1]); } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/call_arguments.rs
crates/rome_js_formatter/src/js/expressions/call_arguments.rs
use crate::context::trailing_comma::FormatTrailingComma; use crate::js::declarations::function_declaration::FormatFunctionOptions; use crate::js::expressions::arrow_function_expression::{ is_multiline_template_starting_on_same_line, FormatJsArrowFunctionExpressionOptions, }; use crate::js::lists::array_element_list::can_concisely_print_array_list; use crate::prelude::*; use crate::utils::function_body::FunctionBodyCacheMode; use crate::utils::test_call::is_test_call_expression; use crate::utils::{is_long_curried_call, write_arguments_multi_line}; use rome_formatter::{format_args, format_element, write, VecBuffer}; use rome_js_syntax::{ AnyJsCallArgument, AnyJsExpression, AnyJsFunctionBody, AnyJsLiteralExpression, AnyJsStatement, AnyTsReturnType, AnyTsType, JsCallArgumentList, JsCallArguments, JsCallArgumentsFields, JsCallExpression, JsExpressionStatement, JsFunctionExpression, JsImportCallExpression, JsLanguage, }; use rome_rowan::{AstSeparatedElement, AstSeparatedList, SyntaxResult}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsCallArguments; impl FormatNodeRule<JsCallArguments> for FormatJsCallArguments { fn fmt_fields(&self, node: &JsCallArguments, f: &mut JsFormatter) -> FormatResult<()> { let JsCallArgumentsFields { l_paren_token, args, r_paren_token, } = node.as_fields(); if args.is_empty() { return write!( f, [ l_paren_token.format(), format_dangling_comments(node.syntax()).with_soft_block_indent(), r_paren_token.format() ] ); } let call_expression = node.parent::<JsCallExpression>(); let (is_commonjs_or_amd_call, is_test_call) = call_expression .as_ref() .map_or((Ok(false), Ok(false)), |call| { ( is_commonjs_or_amd_call(node, call), is_test_call_expression(call), ) }); if is_commonjs_or_amd_call? || is_multiline_template_only_args(node) || is_react_hook_with_deps_array(node, f.comments()) || is_test_call? { return write!( f, [ l_paren_token.format(), format_with(|f| { f.join_with(space()) .entries( args.format_separated(",") .with_trailing_separator(TrailingSeparator::Omit), ) .finish() }), r_paren_token.format() ] ); } let last_index = args.len().saturating_sub(1); let mut has_empty_line = false; let arguments: Vec<_> = args .elements() .enumerate() .map(|(index, element)| { let leading_lines = element .node() .map_or(0, |node| get_lines_before(node.syntax())); has_empty_line = has_empty_line || leading_lines > 1; FormatCallArgument::Default { element, is_last: index == last_index, leading_lines, } }) .collect(); if has_empty_line || is_function_composition_args(node) { return write!( f, [FormatAllArgsBrokenOut { l_paren: &l_paren_token.format(), args: &arguments, r_paren: &r_paren_token.format(), node, expand: true, }] ); } if let Some(group_layout) = arguments_grouped_layout(&args, f.comments()) { write_grouped_arguments(node, arguments, group_layout, f) } else if is_long_curried_call(call_expression.as_ref()) { write!( f, [ l_paren_token.format(), soft_block_indent(&format_once(|f| { write_arguments_multi_line(arguments.iter(), f) })), r_paren_token.format(), ] ) } else { write!( f, [FormatAllArgsBrokenOut { l_paren: &l_paren_token.format(), args: &arguments, r_paren: &r_paren_token.format(), node, expand: false, }] ) } } fn fmt_dangling_comments(&self, _: &JsCallArguments, _: &mut JsFormatter) -> FormatResult<()> { // Formatted inside of `fmt_fields` Ok(()) } } /// Helper for formatting a call argument enum FormatCallArgument { /// Argument that has not been inspected if its formatted content breaks. Default { element: AstSeparatedElement<JsLanguage, AnyJsCallArgument>, /// Whether this is the last element. is_last: bool, /// The number of lines before this node leading_lines: usize, }, /// The argument has been formatted because a caller inspected if it [Self::will_break]. /// /// Allows to re-use the formatted output rather than having to call into the formatting again. Inspected { /// The formatted element content: FormatResult<Option<FormatElement>>, /// The separated element element: AstSeparatedElement<JsLanguage, AnyJsCallArgument>, /// The lines before this element leading_lines: usize, }, } impl FormatCallArgument { /// Returns `true` if this argument contains any content that forces a group to [`break`](FormatElements::will_break). fn will_break(&mut self, f: &mut JsFormatter) -> bool { match &self { FormatCallArgument::Default { element, leading_lines, .. } => { let interned = f.intern(&self); let breaks = match &interned { Ok(Some(element)) => element.will_break(), _ => false, }; *self = FormatCallArgument::Inspected { content: interned, element: element.clone(), leading_lines: *leading_lines, }; breaks } FormatCallArgument::Inspected { content: Ok(Some(result)), .. } => result.will_break(), FormatCallArgument::Inspected { .. } => false, } } /// Formats the node of this argument and caches the function body. /// /// See [JsFormatContext::cached_function_body] /// /// # Panics /// /// If [`cache_function_body`](Self::cache_function_body) or [`will_break`](Self::will_break) has been called on this argument before. fn cache_function_body(&mut self, f: &mut JsFormatter) { match &self { FormatCallArgument::Default { element, leading_lines, .. } => { let interned = f.intern(&format_once(|f| { self.fmt_with_cache_mode(FunctionBodyCacheMode::Cache, f)?; Ok(()) })); *self = FormatCallArgument::Inspected { content: interned, element: element.clone(), leading_lines: *leading_lines, }; } FormatCallArgument::Inspected { .. } => { panic!("`cache` must be called before inspecting or formatting the element."); } } } fn fmt_with_cache_mode( &self, cache_mode: FunctionBodyCacheMode, f: &mut JsFormatter, ) -> FormatResult<()> { match self { // Re-use the cached formatted output if there is any. FormatCallArgument::Inspected { content, .. } => match content.clone()? { Some(element) => { f.write_element(element)?; Ok(()) } None => Ok(()), }, FormatCallArgument::Default { element, is_last, .. } => { match element.node()? { AnyJsCallArgument::AnyJsExpression(AnyJsExpression::JsFunctionExpression( function, )) => { write!( f, [function.format().with_options(FormatFunctionOptions { body_cache_mode: cache_mode, ..FormatFunctionOptions::default() })] )?; } AnyJsCallArgument::AnyJsExpression( AnyJsExpression::JsArrowFunctionExpression(arrow), ) => { write!( f, [arrow .format() .with_options(FormatJsArrowFunctionExpressionOptions { body_cache_mode: cache_mode, ..FormatJsArrowFunctionExpressionOptions::default() })] )?; } node => write!(f, [node.format()])?, } if let Some(separator) = element.trailing_separator()? { if *is_last { write!(f, [format_removed(separator)]) } else { write!(f, [separator.format()]) } } else if !is_last { Err(FormatError::SyntaxError) } else { Ok(()) } } } } /// Returns the number of leading lines before the argument's node fn leading_lines(&self) -> usize { match self { FormatCallArgument::Default { leading_lines, .. } => *leading_lines, FormatCallArgument::Inspected { leading_lines, .. } => *leading_lines, } } /// Returns the [`separated element`](AstSeparatedElement) of this argument. fn element(&self) -> &AstSeparatedElement<JsLanguage, AnyJsCallArgument> { match self { FormatCallArgument::Default { element, .. } => element, FormatCallArgument::Inspected { element, .. } => element, } } } impl Format<JsFormatContext> for FormatCallArgument { fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> { self.fmt_with_cache_mode(FunctionBodyCacheMode::default(), f)?; Ok(()) } } /// Writes the function arguments, and groups the first or last argument depending on `group_layout`. fn write_grouped_arguments( call_arguments: &JsCallArguments, mut arguments: Vec<FormatCallArgument>, group_layout: GroupedCallArgumentLayout, f: &mut JsFormatter, ) -> FormatResult<()> { let l_paren_token = call_arguments.l_paren_token(); let r_paren_token = call_arguments.r_paren_token(); let grouped_breaks = { let (grouped_arg, other_args) = match group_layout { GroupedCallArgumentLayout::GroupedFirstArgument => { let (first, tail) = arguments.split_at_mut(1); (&mut first[0], tail) } GroupedCallArgumentLayout::GroupedLastArgument => { let end_index = arguments.len().saturating_sub(1); let (head, last) = arguments.split_at_mut(end_index); (&mut last[0], head) } }; let non_grouped_breaks = other_args.iter_mut().any(|arg| arg.will_break(f)); // if any of the not grouped elements break, then fall back to the variant where // all arguments are printed in expanded mode. if non_grouped_breaks { return write!( f, [FormatAllArgsBrokenOut { l_paren: &l_paren_token.format(), args: &arguments, r_paren: &r_paren_token.format(), node: call_arguments, expand: true, }] ); } match grouped_arg.element().node()? { AnyJsCallArgument::AnyJsExpression(AnyJsExpression::JsArrowFunctionExpression(_)) => { grouped_arg.cache_function_body(f); } AnyJsCallArgument::AnyJsExpression(AnyJsExpression::JsFunctionExpression(function)) if !other_args.is_empty() && !has_no_parameters(function) => { grouped_arg.cache_function_body(f); } _ => { // Node doesn't have a function body or its a function that doesn't get re-formatted. } } grouped_arg.will_break(f) }; // We now cache them the delimiters tokens. This is needed because `[rome_formatter::best_fitting]` will try to // print each version first // tokens on the left let l_paren = l_paren_token.format().memoized(); // tokens on the right let r_paren = r_paren_token.format().memoized(); // First write the most expanded variant because it needs `arguments`. let most_expanded = { let mut buffer = VecBuffer::new(f.state_mut()); buffer.write_element(FormatElement::Tag(Tag::StartEntry))?; write!( buffer, [FormatAllArgsBrokenOut { l_paren: &l_paren, args: &arguments, r_paren: &r_paren, node: call_arguments, expand: true, }] )?; buffer.write_element(FormatElement::Tag(Tag::EndEntry))?; buffer.into_vec() }; // Now reformat the first or last argument if they happen to be a function or arrow function expression. // Function and arrow function expression apply a custom formatting that removes soft line breaks from the parameters, // type parameters, and return type annotation. // // This implementation caches the function body of the "normal" formatted function or arrow function expression // to avoid quadratic complexity if the functions' body contains another call expression with an arrow or function expression // as first or last argument. let last_index = arguments.len() - 1; let grouped = arguments .into_iter() .enumerate() .map(|(index, argument)| { let layout = match group_layout { GroupedCallArgumentLayout::GroupedFirstArgument if index == 0 => { Some(GroupedCallArgumentLayout::GroupedFirstArgument) } GroupedCallArgumentLayout::GroupedLastArgument if index == last_index => { Some(GroupedCallArgumentLayout::GroupedLastArgument) } _ => None, }; FormatGroupedArgument { argument, single_argument_list: last_index == 0, layout, } .memoized() }) .collect::<Vec<_>>(); // Write the most flat variant with the first or last argument grouped. let most_flat = { let snapshot = f.state_snapshot(); let mut buffer = VecBuffer::new(f.state_mut()); buffer.write_element(FormatElement::Tag(Tag::StartEntry))?; let result = write!( buffer, [ l_paren, format_with(|f| { f.join_with(soft_line_break_or_space()) .entries(grouped.iter()) .finish() }), r_paren ] ); // Turns out, using the grouped layout isn't a good fit because some parameters of the // grouped function or arrow expression break. In that case, fall back to the all args expanded // formatting. // This back tracking is required because testing if the grouped argument breaks would also return `true` // if any content of the function body breaks. But, as far as this is concerned, it's only interested if // any content in the signature breaks. if matches!(result, Err(FormatError::PoorLayout)) { drop(buffer); f.restore_state_snapshot(snapshot); let mut most_expanded_iter = most_expanded.into_iter(); // Skip over the Start/EndEntry items. most_expanded_iter.next(); most_expanded_iter.next_back(); return f.write_elements(most_expanded_iter); } buffer.write_element(FormatElement::Tag(Tag::EndEntry))?; buffer.into_vec().into_boxed_slice() }; // Write the second variant that forces the group of the first/last argument to expand. let middle_variant = { let mut buffer = VecBuffer::new(f.state_mut()); buffer.write_element(FormatElement::Tag(Tag::StartEntry))?; write!( buffer, [ l_paren, format_with(|f| { let mut joiner = f.join_with(soft_line_break_or_space()); match group_layout { GroupedCallArgumentLayout::GroupedFirstArgument => { joiner.entry(&group(&grouped[0]).should_expand(true)); joiner.entries(&grouped[1..]).finish() } GroupedCallArgumentLayout::GroupedLastArgument => { let last_index = grouped.len() - 1; joiner.entries(&grouped[..last_index]); joiner .entry(&group(&grouped[last_index]).should_expand(true)) .finish() } } }), r_paren ] )?; buffer.write_element(FormatElement::Tag(Tag::EndEntry))?; buffer.into_vec().into_boxed_slice() }; if grouped_breaks { write!(f, [expand_parent()])?; } // SAFETY: Safe because variants is guaranteed to contain exactly 3 entries: // * most flat // * middle // * most expanded // ... and best fitting only requires the most flat/and expanded. unsafe { f.write_element(FormatElement::BestFitting( format_element::BestFittingElement::from_vec_unchecked(vec![ most_flat, middle_variant, most_expanded.into_boxed_slice(), ]), )) } } /// Helper for formatting the first grouped argument (see [should_group_first_argument]). struct FormatGroupedFirstArgument<'a> { argument: &'a FormatCallArgument, /// Whether this is the only argument in the argument list. is_only: bool, } impl Format<JsFormatContext> for FormatGroupedFirstArgument<'_> { fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> { use AnyJsExpression::*; let element = self.argument.element(); match element.node()? { // Call the arrow function formatting but explicitly passes the call argument layout down // so that the arrow function formatting removes any soft line breaks between parameters and the return type. AnyJsCallArgument::AnyJsExpression(JsArrowFunctionExpression(arrow)) => { with_token_tracking_disabled(f, |f| { write!( f, [arrow .format() .with_options(FormatJsArrowFunctionExpressionOptions { body_cache_mode: FunctionBodyCacheMode::Cached, call_arg_layout: Some( GroupedCallArgumentLayout::GroupedFirstArgument ), ..FormatJsArrowFunctionExpressionOptions::default() })] )?; match element.trailing_separator()? { None => { if !self.is_only { return Err(FormatError::SyntaxError); } } // The separator is added inside of the arrow function formatting Some(separator) => { if self.is_only { write!(f, [format_removed(separator)])?; } else { write!(f, [separator.format()])?; } } } Ok(()) }) } // For all other nodes, use the normal formatting (which already has been cached) _ => self.argument.fmt(f), } } } /// Helper for formatting the last grouped argument (see [should_group_last_argument]). struct FormatGroupedLastArgument<'a> { argument: &'a FormatCallArgument, /// Is this the only argument in the arguments list is_only: bool, } impl Format<JsFormatContext> for FormatGroupedLastArgument<'_> { fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> { use AnyJsExpression::*; let element = self.argument.element(); // For function and arrow expressions, re-format the node and pass the argument that it is the // last grouped argument. This changes the formatting of parameters, type parameters, and return types // to remove any soft line breaks. match element.node()? { AnyJsCallArgument::AnyJsExpression(JsFunctionExpression(function)) if !self.is_only && !has_no_parameters(function) => { with_token_tracking_disabled(f, |f| { write!( f, [function.format().with_options(FormatFunctionOptions { body_cache_mode: FunctionBodyCacheMode::Cached, call_argument_layout: Some( GroupedCallArgumentLayout::GroupedLastArgument ), })] )?; if let Some(separator) = element.trailing_separator()? { write!(f, [format_removed(separator)])?; } Ok(()) }) } AnyJsCallArgument::AnyJsExpression(JsArrowFunctionExpression(arrow)) => { with_token_tracking_disabled(f, |f| { write!( f, [arrow .format() .with_options(FormatJsArrowFunctionExpressionOptions { body_cache_mode: FunctionBodyCacheMode::Cached, call_arg_layout: Some( GroupedCallArgumentLayout::GroupedLastArgument ), ..FormatJsArrowFunctionExpressionOptions::default() })] )?; if let Some(separator) = element.trailing_separator()? { write!(f, [format_removed(separator)])?; } Ok(()) }) } _ => self.argument.fmt(f), } } } /// Disable the token tracking because it is necessary to format function/arrow expressions slightly different. fn with_token_tracking_disabled<F: FnOnce(&mut JsFormatter) -> R, R>( f: &mut JsFormatter, callback: F, ) -> R { let was_disabled = f.state().is_token_tracking_disabled(); f.state_mut().set_token_tracking_disabled(true); let result = callback(f); f.state_mut().set_token_tracking_disabled(was_disabled); result } /// Tests if `expression` has an empty parameters list. fn has_no_parameters(expression: &JsFunctionExpression) -> bool { match expression.parameters() { // Use default formatting for expressions without parameters, will return `Err` anyway Err(_) => true, Ok(parameters) => parameters.items().is_empty(), } } /// Helper for formatting a grouped call argument (see [should_group_first_argument] and [should_group_last_argument]). struct FormatGroupedArgument { argument: FormatCallArgument, /// Whether this argument is the only argument in the argument list. single_argument_list: bool, /// The layout to use for this argument. layout: Option<GroupedCallArgumentLayout>, } impl Format<JsFormatContext> for FormatGroupedArgument { fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> { match self.layout { Some(GroupedCallArgumentLayout::GroupedFirstArgument) => FormatGroupedFirstArgument { argument: &self.argument, is_only: self.single_argument_list, } .fmt(f), Some(GroupedCallArgumentLayout::GroupedLastArgument) => FormatGroupedLastArgument { argument: &self.argument, is_only: self.single_argument_list, } .fmt(f), None => self.argument.fmt(f), } } } struct FormatAllArgsBrokenOut<'a> { l_paren: &'a dyn Format<JsFormatContext>, args: &'a [FormatCallArgument], r_paren: &'a dyn Format<JsFormatContext>, expand: bool, node: &'a JsCallArguments, } impl<'a> Format<JsFormatContext> for FormatAllArgsBrokenOut<'a> { fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> { let is_inside_import = self.node.parent::<JsImportCallExpression>().is_some(); write!( f, [group(&format_args![ self.l_paren, soft_block_indent(&format_with(|f| { for (index, entry) in self.args.iter().enumerate() { if index > 0 { match entry.leading_lines() { 0 | 1 => write!(f, [soft_line_break_or_space()])?, _ => write!(f, [empty_line()])?, } } write!(f, [entry])?; } if !is_inside_import { write!(f, [FormatTrailingComma::All])?; } Ok(()) })), self.r_paren, ]) .should_expand(self.expand)] ) } } #[derive(Copy, Clone, Debug)] pub enum GroupedCallArgumentLayout { /// Group the first call argument. GroupedFirstArgument, /// Group the last call argument. GroupedLastArgument, } fn arguments_grouped_layout( args: &JsCallArgumentList, comments: &JsComments, ) -> Option<GroupedCallArgumentLayout> { if should_group_first_argument(args, comments).unwrap_or(false) { Some(GroupedCallArgumentLayout::GroupedFirstArgument) } else if should_group_last_argument(args, comments).unwrap_or(false) { Some(GroupedCallArgumentLayout::GroupedLastArgument) } else { None } } /// Checks if the the first argument requires grouping fn should_group_first_argument( list: &JsCallArgumentList, comments: &JsComments, ) -> SyntaxResult<bool> { use AnyJsExpression::*; let mut iter = list.iter(); match (iter.next(), iter.next()) { ( Some(Ok(AnyJsCallArgument::AnyJsExpression(first))), Some(Ok(AnyJsCallArgument::AnyJsExpression(second))), ) if iter.next().is_none() => { match &first { JsFunctionExpression(_) => {} JsArrowFunctionExpression(arrow) => { if !matches!(arrow.body(), Ok(AnyJsFunctionBody::JsFunctionBody(_))) { return Ok(false); } } _ => return Ok(false), }; if matches!( second, JsArrowFunctionExpression(_) | JsFunctionExpression(_) | JsConditionalExpression(_) ) { return Ok(false); } Ok(!comments.has_comments(first.syntax()) && !can_group_expression_argument(&second, false, comments)?) } _ => Ok(false), } } /// Checks if the last argument should be grouped. fn should_group_last_argument( list: &JsCallArgumentList, comments: &JsComments, ) -> SyntaxResult<bool> { use AnyJsExpression::*; let mut iter = list.iter(); let last = iter.next_back(); match last { Some(Ok(AnyJsCallArgument::AnyJsExpression(last))) => { if comments.has_leading_comments(last.syntax()) || comments.has_trailing_comments(last.syntax()) { return Ok(false); } if !can_group_expression_argument(&last, false, comments)? { return Ok(false); } let penultimate = iter.next_back(); if let Some(Ok(penultimate)) = &penultimate { if penultimate.syntax().kind() == last.syntax().kind() { return Ok(false); } } match last { JsArrayExpression(array) if list.len() > 1 => { // Not for `useEffect` if list.len() == 2 && matches!( penultimate, Some(Ok(AnyJsCallArgument::AnyJsExpression( JsArrowFunctionExpression(_) ))) ) { return Ok(false); } if can_concisely_print_array_list(&array.elements(), comments) { return Ok(false); } Ok(true) } _ => Ok(true), } } _ => Ok(false), } } /// Checks if `argument` benefits from grouping in call arguments. fn can_group_expression_argument( argument: &AnyJsExpression, is_arrow_recursion: bool, comments: &JsComments, ) -> SyntaxResult<bool> { use AnyJsExpression::*; let result = match argument { JsObjectExpression(object_expression) => { !object_expression.members().is_empty() || comments.has_comments(object_expression.syntax()) } JsArrayExpression(array_expression) => { !array_expression.elements().is_empty() || comments.has_comments(array_expression.syntax()) } TsTypeAssertionExpression(assertion_expression) => { can_group_expression_argument(&assertion_expression.expression()?, false, comments)? } TsAsExpression(as_expression) => { can_group_expression_argument(&as_expression.expression()?, false, comments)? } TsSatisfiesExpression(satisfies_expression) => { can_group_expression_argument(&satisfies_expression.expression()?, false, comments)? } JsArrowFunctionExpression(arrow_function) => { let body = arrow_function.body()?; let return_type_annotation = arrow_function.return_type_annotation(); // Handles cases like: // // app.get("/", (req, res): void => { // res.send("Hello World!"); // }); // // export class Thing implements OtherThing { // do: (type: Type) => Provider<Prop> = memoize( // (type: ObjectType): Provider<Opts> => {} // ); // } let can_group_type =
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
true
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/super_expression.rs
crates/rome_js_formatter/src/js/expressions/super_expression.rs
use crate::prelude::*; use rome_formatter::write; use crate::parentheses::NeedsParentheses; use rome_js_syntax::JsSuperExpressionFields; use rome_js_syntax::{JsSuperExpression, JsSyntaxNode}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsSuperExpression; impl FormatNodeRule<JsSuperExpression> for FormatJsSuperExpression { fn fmt_fields(&self, node: &JsSuperExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsSuperExpressionFields { super_token } = node.as_fields(); write![f, [super_token.format()]] } fn needs_parentheses(&self, item: &JsSuperExpression) -> bool { item.needs_parentheses() } } impl NeedsParentheses for JsSuperExpression { #[inline(always)] fn needs_parentheses(&self) -> bool { false } #[inline(always)] fn needs_parentheses_with_parent(&self, _parent: &JsSyntaxNode) -> bool { false } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/yield_expression.rs
crates/rome_js_formatter/src/js/expressions/yield_expression.rs
use crate::prelude::*; use rome_formatter::write; use crate::js::expressions::await_expression::await_or_yield_needs_parens; use crate::parentheses::NeedsParentheses; use rome_js_syntax::{JsSyntaxKind, JsYieldExpressionFields}; use rome_js_syntax::{JsSyntaxNode, JsYieldExpression}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsYieldExpression; impl FormatNodeRule<JsYieldExpression> for FormatJsYieldExpression { fn fmt_fields(&self, node: &JsYieldExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsYieldExpressionFields { yield_token, argument, } = node.as_fields(); write![f, [yield_token.format(), argument.format()]] } fn needs_parentheses(&self, item: &JsYieldExpression) -> bool { item.needs_parentheses() } } impl NeedsParentheses for JsYieldExpression { fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool { matches!(parent.kind(), JsSyntaxKind::JS_AWAIT_EXPRESSION) || await_or_yield_needs_parens(parent, self.syntax()) } } #[cfg(test)] mod tests { use crate::{assert_needs_parentheses, assert_not_needs_parentheses}; use rome_js_syntax::JsYieldExpression; #[test] fn needs_parentheses() { assert_needs_parentheses!( "function* test() { (yield a)`template` }", JsYieldExpression ); assert_needs_parentheses!("function* test() { +(yield a) }", JsYieldExpression); assert_needs_parentheses!("function* test() { (yield a).b }", JsYieldExpression); assert_needs_parentheses!("function* test() { (yield a)[b] }", JsYieldExpression); assert_not_needs_parentheses!("function* test() { a[yield b] }", JsYieldExpression); assert_needs_parentheses!("function* test() { (yield a)() }", JsYieldExpression); assert_needs_parentheses!("function* test() { new (yield a)() }", JsYieldExpression); assert_needs_parentheses!("function* test() { (yield a) && b }", JsYieldExpression); assert_needs_parentheses!("function* test() { (yield a) + b }", JsYieldExpression); assert_needs_parentheses!( "function* test() { (yield a) instanceof b }", JsYieldExpression ); assert_needs_parentheses!("function* test() { (yield a) in b }", JsYieldExpression); assert_needs_parentheses!("function* test() { [...(yield a)] }", JsYieldExpression); assert_needs_parentheses!("function* test() { ({...(yield b)}) }", JsYieldExpression); assert_needs_parentheses!("function* test() { call(...(yield b)) }", JsYieldExpression); assert_needs_parentheses!( "function* test() { class A extends (yield b) {} }", JsYieldExpression ); assert_needs_parentheses!( "function* test() { (yield b) as number }", JsYieldExpression ); assert_needs_parentheses!("function* test() { (yield b)! }", JsYieldExpression); assert_needs_parentheses!("function* test() { (yield b) ? b : c }", JsYieldExpression); assert_not_needs_parentheses!("function* test() { a ? yield b : c }", JsYieldExpression); assert_not_needs_parentheses!("function* test() { a ? b : yield c }", JsYieldExpression); } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/assignment_expression.rs
crates/rome_js_formatter/src/js/expressions/assignment_expression.rs
use crate::prelude::*; use crate::utils::AnyJsAssignmentLike; use crate::parentheses::{ is_arrow_function_body, is_first_in_statement, FirstInStatementMode, NeedsParentheses, }; use rome_formatter::write; use rome_js_syntax::{ AnyJsAssignmentPattern, AnyJsForInitializer, JsArrowFunctionExpression, JsAssignmentExpression, JsComputedMemberName, JsExpressionStatement, JsForStatement, JsSequenceExpression, JsSyntaxKind, JsSyntaxNode, }; use rome_rowan::{match_ast, AstNode}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsAssignmentExpression; impl FormatNodeRule<JsAssignmentExpression> for FormatJsAssignmentExpression { fn fmt_fields(&self, node: &JsAssignmentExpression, f: &mut JsFormatter) -> FormatResult<()> { write![f, [AnyJsAssignmentLike::from(node.clone())]] } fn needs_parentheses(&self, item: &JsAssignmentExpression) -> bool { item.needs_parentheses() } } impl NeedsParentheses for JsAssignmentExpression { fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool { match_ast! { match parent { JsAssignmentExpression(_) => false, // `[a = b]` JsComputedMemberName(_) => false, JsArrowFunctionExpression(_) => { is_arrow_function_body(self.syntax(), parent) }, JsForStatement(for_statement) => { let is_initializer = match for_statement.initializer() { Some(AnyJsForInitializer::AnyJsExpression(expression)) => { expression.syntax() == self.syntax() } None | Some(_) => false, }; let is_update = for_statement .update() .map(AstNode::into_syntax) .as_ref() == Some(self.syntax()); !(is_initializer || is_update) }, JsExpressionStatement(_) => { // Parenthesize `{ a } = { a: 5 }` is_first_in_statement( self.clone().into(), FirstInStatementMode::ExpressionStatementOrArrow, ) && matches!( self.left(), Ok(AnyJsAssignmentPattern::JsObjectAssignmentPattern(_)) ) }, JsSequenceExpression(_) => { let mut child = parent.clone(); for ancestor in parent.ancestors().skip(1) { match ancestor.kind() { JsSyntaxKind::JS_SEQUENCE_EXPRESSION | JsSyntaxKind::JS_PARENTHESIZED_EXPRESSION => child = ancestor, JsSyntaxKind::JS_FOR_STATEMENT => { let for_statement = JsForStatement::unwrap_cast(ancestor); let is_initializer = match for_statement.initializer() { Some(AnyJsForInitializer::AnyJsExpression(expression)) => { expression.syntax() == &child } None | Some(_) => false, }; let is_update = for_statement.update().map(AstNode::into_syntax).as_ref() == Some(&child); return !(is_initializer || is_update); } _ => break, } } true }, _ => { true } } } } } #[cfg(test)] mod tests { use crate::{assert_needs_parentheses, assert_not_needs_parentheses}; use rome_js_syntax::JsAssignmentExpression; #[test] fn needs_parentheses() { assert_not_needs_parentheses!("({ [a = 3]: value })", JsAssignmentExpression); assert_not_needs_parentheses!("class Test { [a = 3]: value }", JsAssignmentExpression); assert_not_needs_parentheses!("type Test = { [a = 3]: value }", JsAssignmentExpression); assert_not_needs_parentheses!("interface Test { [a = 3]: value }", JsAssignmentExpression); assert_needs_parentheses!("a => (a = 3)", JsAssignmentExpression); assert_not_needs_parentheses!("a => { a = 3 }", JsAssignmentExpression); assert_not_needs_parentheses!("for(a = 3;;) {}", JsAssignmentExpression); assert_not_needs_parentheses!("for(a = 3, b = 2;;) {}", JsAssignmentExpression[1]); assert_not_needs_parentheses!("for(a = 3, b = 2, c= 3;;) {}", JsAssignmentExpression[2]); assert_needs_parentheses!("for(; a = 3; ) {}", JsAssignmentExpression); assert_not_needs_parentheses!("for(;;a = 3) {}", JsAssignmentExpression); assert_not_needs_parentheses!("for ((a, a = 3);;) {}", JsAssignmentExpression); assert_needs_parentheses!("for (; (a, a = 3);) {}", JsAssignmentExpression); assert_not_needs_parentheses!("for (;;(a, a = 3)) {}", JsAssignmentExpression); assert_not_needs_parentheses!("a = 3", JsAssignmentExpression); assert_needs_parentheses!("({ a } = { a: 3 })", JsAssignmentExpression); } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/function_expression.rs
crates/rome_js_formatter/src/js/expressions/function_expression.rs
use crate::prelude::*; use crate::js::declarations::function_declaration::{FormatFunction, FormatFunctionOptions}; use crate::parentheses::{ is_callee, is_first_in_statement, is_tag, FirstInStatementMode, NeedsParentheses, }; use rome_formatter::FormatRuleWithOptions; use rome_js_syntax::{JsFunctionExpression, JsSyntaxNode}; #[derive(Debug, Copy, Clone, Default)] pub(crate) struct FormatJsFunctionExpression { options: FormatFunctionOptions, } impl FormatRuleWithOptions<JsFunctionExpression> for FormatJsFunctionExpression { type Options = FormatFunctionOptions; fn with_options(mut self, options: Self::Options) -> Self { self.options = options; self } } impl FormatNodeRule<JsFunctionExpression> for FormatJsFunctionExpression { fn fmt_fields(&self, node: &JsFunctionExpression, f: &mut JsFormatter) -> FormatResult<()> { FormatFunction::from(node.clone()).fmt_with_options(f, &self.options)?; Ok(()) } fn needs_parentheses(&self, item: &JsFunctionExpression) -> bool { item.needs_parentheses() } } impl NeedsParentheses for JsFunctionExpression { fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool { is_callee(self.syntax(), parent) || is_tag(self.syntax(), parent) || is_first_in_statement( self.clone().into(), FirstInStatementMode::ExpressionOrExportDefault, ) } } #[cfg(test)] mod tests { use crate::{assert_needs_parentheses, assert_not_needs_parentheses}; use rome_js_syntax::JsFunctionExpression; #[test] fn needs_parentheses() { assert_needs_parentheses!("console.log((function () {})())", JsFunctionExpression); assert_needs_parentheses!("console.log(new (function () {})())", JsFunctionExpression); assert_needs_parentheses!("(function() {}).test", JsFunctionExpression); assert_not_needs_parentheses!("a => function () {} ", JsFunctionExpression); assert_needs_parentheses!( "console.log((function () {})`template`)", JsFunctionExpression ); assert_needs_parentheses!("export default (function () {})", JsFunctionExpression); } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/yield_argument.rs
crates/rome_js_formatter/src/js/expressions/yield_argument.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::JsYieldArgument; use rome_js_syntax::JsYieldArgumentFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsYieldArgument; impl FormatNodeRule<JsYieldArgument> for FormatJsYieldArgument { fn fmt_fields(&self, node: &JsYieldArgument, f: &mut JsFormatter) -> FormatResult<()> { let JsYieldArgumentFields { star_token, expression, } = node.as_fields(); write![f, [star_token.format(), space(), expression.format()]] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/import_meta_expression.rs
crates/rome_js_formatter/src/js/expressions/import_meta_expression.rs
use crate::prelude::*; use crate::parentheses::NeedsParentheses; use rome_formatter::write; use rome_js_syntax::JsImportMetaExpressionFields; use rome_js_syntax::{JsImportMetaExpression, JsSyntaxNode}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsImportMetaExpression; impl FormatNodeRule<JsImportMetaExpression> for FormatJsImportMetaExpression { fn fmt_fields(&self, node: &JsImportMetaExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsImportMetaExpressionFields { import_token, dot_token, meta_token, } = node.as_fields(); write![ f, [ import_token.format(), dot_token.format(), meta_token.format(), ] ] } fn needs_parentheses(&self, item: &JsImportMetaExpression) -> bool { item.needs_parentheses() } } impl NeedsParentheses for JsImportMetaExpression { fn needs_parentheses(&self) -> bool { false } fn needs_parentheses_with_parent(&self, _parent: &JsSyntaxNode) -> bool { false } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/this_expression.rs
crates/rome_js_formatter/src/js/expressions/this_expression.rs
use crate::prelude::*; use rome_formatter::write; use crate::parentheses::NeedsParentheses; use rome_js_syntax::JsThisExpressionFields; use rome_js_syntax::{JsSyntaxNode, JsThisExpression}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsThisExpression; impl FormatNodeRule<JsThisExpression> for FormatJsThisExpression { fn fmt_fields(&self, node: &JsThisExpression, f: &mut JsFormatter) -> FormatResult<()> { let JsThisExpressionFields { this_token } = node.as_fields(); write![f, [this_token.format()]] } fn needs_parentheses(&self, item: &JsThisExpression) -> bool { item.needs_parentheses() } } impl NeedsParentheses for JsThisExpression { #[inline(always)] fn needs_parentheses(&self) -> bool { false } #[inline(always)] fn needs_parentheses_with_parent(&self, _parent: &JsSyntaxNode) -> bool { false } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/binary_expression.rs
crates/rome_js_formatter/src/js/expressions/binary_expression.rs
use crate::prelude::*; use crate::utils::{needs_binary_like_parentheses, AnyJsBinaryLikeExpression}; use crate::parentheses::NeedsParentheses; use rome_js_syntax::{JsBinaryExpression, JsSyntaxNode}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsBinaryExpression; impl FormatNodeRule<JsBinaryExpression> for FormatJsBinaryExpression { fn fmt_fields( &self, node: &JsBinaryExpression, formatter: &mut JsFormatter, ) -> FormatResult<()> { AnyJsBinaryLikeExpression::JsBinaryExpression(node.clone()).fmt(formatter) } fn needs_parentheses(&self, item: &JsBinaryExpression) -> bool { item.needs_parentheses() } } impl NeedsParentheses for JsBinaryExpression { fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool { needs_binary_like_parentheses(&AnyJsBinaryLikeExpression::from(self.clone()), parent) } } #[cfg(test)] mod tests { use crate::{assert_needs_parentheses, assert_not_needs_parentheses}; use rome_js_syntax::{JsBinaryExpression, JsFileSource}; #[test] fn needs_parentheses() { assert_needs_parentheses!("class X extends (4 + 4) {}", JsBinaryExpression); assert_needs_parentheses!("(4 + 4) as number", JsBinaryExpression); assert_needs_parentheses!("<number>(4 + 4)", JsBinaryExpression); assert_needs_parentheses!("!(4 + 4)", JsBinaryExpression); assert_needs_parentheses!("await (4 + 4)", JsBinaryExpression); assert_needs_parentheses!("(4 + 4)!", JsBinaryExpression); assert_needs_parentheses!("(4 + 4)()", JsBinaryExpression); assert_needs_parentheses!("(4 + 4)?.()", JsBinaryExpression); assert_needs_parentheses!("new (4 + 4)()", JsBinaryExpression); assert_needs_parentheses!("(4 + 4)`template`", JsBinaryExpression); assert_needs_parentheses!("[...(4 + 4)]", JsBinaryExpression); assert_needs_parentheses!("({...(4 + 4)})", JsBinaryExpression); assert_needs_parentheses!( "<test {...(4 + 4)} />", JsBinaryExpression, JsFileSource::tsx() ); assert_needs_parentheses!( "<test>{...(4 + 4)}</test>", JsBinaryExpression, JsFileSource::tsx() ); assert_needs_parentheses!("(4 + 4).member", JsBinaryExpression); assert_needs_parentheses!("(4 + 4)[member]", JsBinaryExpression); assert_not_needs_parentheses!("object[4 + 4]", JsBinaryExpression); assert_needs_parentheses!("(4 + 4) * 3", JsBinaryExpression[1]); assert_not_needs_parentheses!("(4 + 4) * 3", JsBinaryExpression[0]); assert_needs_parentheses!("a ** b ** c", JsBinaryExpression[1]); assert_not_needs_parentheses!("a ** b ** c", JsBinaryExpression[0]); assert_needs_parentheses!("a * r >> 5", JsBinaryExpression[1]); assert_not_needs_parentheses!("a * r >> 5", JsBinaryExpression[0]); assert_needs_parentheses!("a * r | 4", JsBinaryExpression[1]); assert_not_needs_parentheses!("a * r | 5", JsBinaryExpression[0]); assert_needs_parentheses!("a % 4 + 4", JsBinaryExpression[1]); assert_not_needs_parentheses!("a % 4 + 4", JsBinaryExpression[0]); assert_needs_parentheses!("a == b == c", JsBinaryExpression[1]); assert_not_needs_parentheses!("a == b == c", JsBinaryExpression[0]); } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/expressions/arrow_function_expression.rs
crates/rome_js_formatter/src/js/expressions/arrow_function_expression.rs
use crate::prelude::*; use rome_formatter::{ format_args, write, CstFormatContext, FormatRuleWithOptions, RemoveSoftLinesBuffer, }; use std::iter::once; use crate::context::trailing_comma::FormatTrailingComma; use crate::js::expressions::call_arguments::GroupedCallArgumentLayout; use crate::parentheses::{ is_binary_like_left_or_right, is_callee, is_conditional_test, update_or_lower_expression_needs_parentheses, AnyJsExpressionLeftSide, NeedsParentheses, }; use crate::utils::function_body::{FormatMaybeCachedFunctionBody, FunctionBodyCacheMode}; use crate::utils::test_call::is_test_call_argument; use crate::utils::{resolve_left_most_expression, AssignmentLikeLayout}; use rome_js_syntax::{ AnyJsArrowFunctionParameters, AnyJsBindingPattern, AnyJsExpression, AnyJsFormalParameter, AnyJsFunctionBody, AnyJsParameter, AnyJsTemplateElement, JsArrowFunctionExpression, JsFormalParameter, JsSyntaxKind, JsSyntaxNode, JsTemplateExpression, }; use rome_rowan::{SyntaxNodeOptionExt, SyntaxResult}; #[derive(Debug, Copy, Clone, Default)] pub(crate) struct FormatJsArrowFunctionExpression { options: FormatJsArrowFunctionExpressionOptions, } #[derive(Debug, Clone, Copy, Default)] pub(crate) struct FormatJsArrowFunctionExpressionOptions { pub assignment_layout: Option<AssignmentLikeLayout>, pub call_arg_layout: Option<GroupedCallArgumentLayout>, pub body_cache_mode: FunctionBodyCacheMode, } impl FormatRuleWithOptions<JsArrowFunctionExpression> for FormatJsArrowFunctionExpression { type Options = FormatJsArrowFunctionExpressionOptions; fn with_options(mut self, options: Self::Options) -> Self { self.options = options; self } } impl FormatNodeRule<JsArrowFunctionExpression> for FormatJsArrowFunctionExpression { fn fmt_fields( &self, node: &JsArrowFunctionExpression, f: &mut JsFormatter, ) -> FormatResult<()> { let layout = ArrowFunctionLayout::for_arrow(node.clone(), f.context().comments(), &self.options)?; match layout { ArrowFunctionLayout::Chain(chain) => { write!(f, [chain]) } ArrowFunctionLayout::Single(arrow) => { use self::AnyJsExpression::*; use AnyJsFunctionBody::*; let body = arrow.body()?; let format_signature = format_with(|f| { write!( f, [ format_signature(&arrow, self.options.call_arg_layout.is_some()), space(), arrow.fat_arrow_token().format() ] ) }); let format_body = FormatMaybeCachedFunctionBody { body: &body, mode: self.options.body_cache_mode, }; // With arrays, arrow selfs and objects, they have a natural line breaking strategy: // Arrays and objects become blocks: // // [ // 100000, // 200000, // 300000 // ] // // Arrow selfs get line broken after the `=>`: // // (foo) => (bar) => // (foo + bar) * (foo + bar) // // Therefore if our body is an arrow self, array, or object, we // do not have a soft line break after the arrow because the body is // going to get broken anyways. let body_has_soft_line_break = match &body { JsFunctionBody(_) | AnyJsExpression( JsArrowFunctionExpression(_) | JsArrayExpression(_) | JsObjectExpression(_), ) => !f.comments().has_leading_own_line_comment(body.syntax()), AnyJsExpression(JsxTagExpression(_)) => true, AnyJsExpression(JsTemplateExpression(template)) => { is_multiline_template_starting_on_same_line(template) } AnyJsExpression(JsSequenceExpression(_)) => { return write!( f, [group(&format_args![ format_signature, group(&format_args![ space(), text("("), soft_block_indent(&format_body), text(")") ]) ])] ); } _ => false, }; if body_has_soft_line_break { write![f, [format_signature, space(), format_body]] } else { // Add parentheses to avoid confusion between `a => b ? c : d` and `a <= b ? c : d` // but only if the body isn't an object/function or class expression because parentheses are always required in that // case and added by the object expression itself let should_add_parens = match &body { AnyJsExpression(expression @ JsConditionalExpression(_)) => { let are_parentheses_mandatory = matches!( resolve_left_most_expression(expression), AnyJsExpressionLeftSide::AnyJsExpression( JsObjectExpression(_) | JsFunctionExpression(_) | JsClassExpression(_) ) ); !are_parentheses_mandatory } _ => false, }; let is_last_call_arg = matches!( self.options.call_arg_layout, Some(GroupedCallArgumentLayout::GroupedLastArgument) ); let should_add_soft_line = (is_last_call_arg // if it's inside a JSXExpression (e.g. an attribute) we should align the expression's closing } with the line with the opening {. || matches!(node.syntax().parent().kind(), Some(JsSyntaxKind::JSX_EXPRESSION_CHILD | JsSyntaxKind::JSX_EXPRESSION_ATTRIBUTE_VALUE))) && !f.context().comments().has_comments(node.syntax()); write!( f, [ format_signature, group(&format_args![ soft_line_indent_or_space(&format_with(|f| { if should_add_parens { write!(f, [if_group_fits_on_line(&text("("))])?; } write!(f, [format_body])?; if should_add_parens { write!(f, [if_group_fits_on_line(&text(")"))])?; } Ok(()) })), is_last_call_arg.then_some(format_args![FormatTrailingComma::All,]), should_add_soft_line.then_some(format_args![soft_line_break()]) ]) ] ) } } } } fn needs_parentheses(&self, item: &JsArrowFunctionExpression) -> bool { item.needs_parentheses() } fn fmt_dangling_comments( &self, _: &JsArrowFunctionExpression, _: &mut JsFormatter, ) -> FormatResult<()> { // Formatted inside of `fmt_fields` Ok(()) } } /// Writes the arrow function type parameters, parameters, and return type annotation. /// /// Formats the parameters and return type annotation without any soft line breaks if `is_first_or_last_call_argument` is `true` /// so that the parameters and return type are kept on the same line. /// /// # Errors /// /// Returns [`FormatError::PoorLayout`] if `is_first_or_last_call_argument` is `true` but the parameters /// or return type annotation contain any content that forces a [*group to break](FormatElements::will_break). /// /// This error gets captured by [FormatJsCallArguments]. fn format_signature( arrow: &JsArrowFunctionExpression, is_first_or_last_call_argument: bool, ) -> impl Format<JsFormatContext> + '_ { format_with(move |f| { if let Some(async_token) = arrow.async_token() { write!(f, [async_token.format(), space()])?; } let format_parameters = format_with(|f: &mut JsFormatter| { write!(f, [arrow.type_parameters().format()])?; match arrow.parameters()? { AnyJsArrowFunctionParameters::AnyJsBinding(binding) => { let should_hug = is_test_call_argument(arrow.syntax())?; let parentheses_not_needed = can_avoid_parentheses(arrow, f); if !parentheses_not_needed { write!(f, [text("(")])?; } if should_hug { write!(f, [binding.format()])?; } else { write!( f, [&soft_block_indent(&format_args![ binding.format(), FormatTrailingComma::All ])] )? } if !parentheses_not_needed { write!(f, [text(")")])?; } } AnyJsArrowFunctionParameters::JsParameters(params) => { write!(f, [params.format()])?; } }; Ok(()) }); if is_first_or_last_call_argument { let mut buffer = RemoveSoftLinesBuffer::new(f); let mut recording = buffer.start_recording(); write!( recording, [group(&format_args![ group(&format_parameters), group(&arrow.return_type_annotation().format()) ])] )?; if recording.stop().will_break() { return Err(FormatError::PoorLayout); } } else { write!( f, [group(&format_args![ format_parameters, arrow.return_type_annotation().format() ])] )?; } if f.comments().has_dangling_comments(arrow.syntax()) { write!(f, [space(), format_dangling_comments(arrow.syntax())])?; } Ok(()) }) } fn should_break_chain(arrow: &JsArrowFunctionExpression) -> SyntaxResult<bool> { if arrow.type_parameters().is_some() { return Ok(true); } let parameters = arrow.parameters()?; let has_parameters = match &parameters { AnyJsArrowFunctionParameters::AnyJsBinding(_) => true, AnyJsArrowFunctionParameters::JsParameters(parameters) => !parameters.items().is_empty(), }; if arrow.return_type_annotation().is_some() && has_parameters { return Ok(true); } // Break if the function has any rest, object, or array parameter let result = has_rest_object_or_array_parameter(&parameters); Ok(result) } fn has_rest_object_or_array_parameter(parameters: &AnyJsArrowFunctionParameters) -> bool { match parameters { AnyJsArrowFunctionParameters::AnyJsBinding(_) => false, AnyJsArrowFunctionParameters::JsParameters(parameters) => parameters .items() .iter() .flatten() .any(|parameter| match parameter { AnyJsParameter::AnyJsFormalParameter(AnyJsFormalParameter::JsFormalParameter( parameter, )) => { matches!( parameter.binding(), Ok(AnyJsBindingPattern::JsArrayBindingPattern(_) | AnyJsBindingPattern::JsObjectBindingPattern(_)) ) } AnyJsParameter::AnyJsFormalParameter(AnyJsFormalParameter::JsBogusParameter(_)) => { false } AnyJsParameter::TsThisParameter(_) => false, AnyJsParameter::JsRestParameter(_) => true, }), } } /// Returns `true` if parentheses can be safely avoided and the `arrow_parentheses` formatter option allows it pub fn can_avoid_parentheses(arrow: &JsArrowFunctionExpression, f: &mut JsFormatter) -> bool { arrow.parameters().map_or(false, |parameters| { f.options().arrow_parentheses().is_as_needed() && parameters.len() == 1 && arrow.type_parameters().is_none() && arrow.return_type_annotation().is_none() && !has_rest_object_or_array_parameter(&parameters) && !parameters .as_js_parameters() .and_then(|p| p.items().first()?.ok()) .and_then(|p| JsFormalParameter::cast(p.syntax().clone())) .is_some_and(|p| { f.context().comments().has_comments(p.syntax()) || p.initializer().is_some() || p.question_mark_token().is_some() || p.type_annotation().is_some() }) }) } #[derive(Clone, Debug)] enum ArrowFunctionLayout { /// Arrow function with a non-arrow function body Single(JsArrowFunctionExpression), /// A chain of at least two arrow functions. /// /// An arrow function is part of the chain when it is the body of the parent arrow function. /// /// The idea of arrow chains is that they break after the `=>` token /// /// ```javascript /// const x = /// (a): string => /// (b) => /// (c) => /// (d) => /// (e) => /// f; /// ``` Chain(ArrowChain), } #[derive(Clone, Debug)] struct ArrowChain { /// The top most arrow function in the chain head: JsArrowFunctionExpression, /// The arrow functions in the chain that are neither the first nor the last. /// Empty for chains consisting only of two arrow functions. middle: Vec<JsArrowFunctionExpression>, /// The last arrow function in the chain tail: JsArrowFunctionExpression, options: FormatJsArrowFunctionExpressionOptions, /// Whether the group wrapping the signatures should be expanded or not. expand_signatures: bool, } impl ArrowChain { /// Returns an iterator over all arrow functions in this chain fn arrows(&self) -> impl Iterator<Item = &JsArrowFunctionExpression> { once(&self.head) .chain(self.middle.iter()) .chain(once(&self.tail)) } } impl Format<JsFormatContext> for ArrowChain { fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> { let ArrowChain { head, tail, expand_signatures, .. } = self; let head_parent = head.syntax().parent(); let tail_body = tail.body()?; let is_assignment_rhs = self.options.assignment_layout.is_some(); let is_callee = head_parent .as_ref() .map_or(false, |parent| is_callee(head.syntax(), parent)); let body_on_separate_line = !matches!( tail_body, AnyJsFunctionBody::JsFunctionBody(_) | AnyJsFunctionBody::AnyJsExpression( AnyJsExpression::JsObjectExpression(_) | AnyJsExpression::JsSequenceExpression(_) ) ); let break_before_chain = (is_callee && body_on_separate_line) || matches!( self.options.assignment_layout, Some(AssignmentLikeLayout::ChainTailArrowFunction) ); let format_arrow_signatures = format_with(|f| { if is_callee || is_assignment_rhs { write!(f, [soft_line_break()])?; } let join_signatures = format_with(|f| { for arrow in self.arrows() { write!( f, [ format_leading_comments(arrow.syntax()), format_signature(arrow, self.options.call_arg_layout.is_some()) ] )?; // The arrow of the tail is formatted outside of the group to ensure it never // breaks from the body if arrow != tail { write!( f, [ space(), arrow.fat_arrow_token().format(), soft_line_break_or_space() ] )?; } } Ok(()) }); write!( f, [group(&join_signatures).should_expand(*expand_signatures)] ) }); let format_tail_body_inner = format_with(|f| { let format_tail_body = FormatMaybeCachedFunctionBody { body: &tail_body, mode: self.options.body_cache_mode, }; // Ensure that the parens of sequence expressions end up on their own line if the // body breaks if matches!( tail_body, AnyJsFunctionBody::AnyJsExpression(AnyJsExpression::JsSequenceExpression(_)) ) { write!( f, [group(&format_args![ text("("), soft_block_indent(&format_tail_body), text(")") ])] )?; } else { write!(f, [format_tail_body])?; } // Format the trailing comments of all arrow function EXCEPT the first one because // the comments of the head get formatted as part of the `FormatJsArrowFunctionExpression` call. for arrow in self.arrows().skip(1) { write!(f, [format_trailing_comments(arrow.syntax())])?; } Ok(()) }); let format_tail_body = format_with(|f| { if body_on_separate_line { write!( f, [indent(&format_args![ soft_line_break_or_space(), format_tail_body_inner ])] ) } else { write!(f, [space(), format_tail_body_inner]) } }); let group_id = f.group_id("arrow-chain"); let format_inner = format_once(|f| { write!( f, [ group(&indent(&format_arrow_signatures)) .with_group_id(Some(group_id)) .should_expand(break_before_chain), space(), tail.fat_arrow_token().format(), indent_if_group_breaks(&format_tail_body, group_id), ] )?; if is_callee { write!( f, [if_group_breaks(&soft_line_break()).with_group_id(Some(group_id))] )?; } Ok(()) }); write!(f, [group(&format_inner)]) } } impl ArrowFunctionLayout { /// Determines the layout for the passed arrow function. See [ArrowFunctionLayout] for a description /// of the different layouts. fn for_arrow( arrow: JsArrowFunctionExpression, comments: &JsComments, options: &FormatJsArrowFunctionExpressionOptions, ) -> SyntaxResult<ArrowFunctionLayout> { let mut head = None; let mut middle = Vec::new(); let mut current = arrow; let mut should_break = false; let result = loop { match current.body()? { AnyJsFunctionBody::AnyJsExpression(AnyJsExpression::JsArrowFunctionExpression( next, )) if matches!( options.call_arg_layout, None | Some(GroupedCallArgumentLayout::GroupedLastArgument) ) && !comments.is_suppressed(next.syntax()) => { should_break = should_break || should_break_chain(&current)?; if head.is_none() { head = Some(current); } else { middle.push(current); } current = next; } _ => { break match head { None => ArrowFunctionLayout::Single(current), Some(head) => ArrowFunctionLayout::Chain(ArrowChain { head, middle, tail: current, expand_signatures: should_break, options: *options, }), } } } }; Ok(result) } } impl NeedsParentheses for JsArrowFunctionExpression { fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool { match parent.kind() { JsSyntaxKind::TS_AS_EXPRESSION | JsSyntaxKind::TS_SATISFIES_EXPRESSION | JsSyntaxKind::JS_UNARY_EXPRESSION | JsSyntaxKind::JS_AWAIT_EXPRESSION | JsSyntaxKind::TS_TYPE_ASSERTION_EXPRESSION => true, _ => { is_conditional_test(self.syntax(), parent) || update_or_lower_expression_needs_parentheses(self.syntax(), parent) || is_binary_like_left_or_right(self.syntax(), parent) } } } } /// Returns `true` if the template contains any new lines inside of its text chunks. fn template_literal_contains_new_line(template: &JsTemplateExpression) -> bool { template.elements().iter().any(|element| match element { AnyJsTemplateElement::JsTemplateChunkElement(chunk) => chunk .template_chunk_token() .map_or(false, |chunk| chunk.text().contains('\n')), AnyJsTemplateElement::JsTemplateElement(_) => false, }) } /// Returns `true` for a template that starts on the same line as the previous token and contains a line break. /// /// /// # Examples // /// ```javascript /// "test" + ` /// some content /// `; /// ``` /// /// Returns `true` because the template starts on the same line as the `+` token and its text contains a line break. /// /// ```javascript /// "test" + `no line break` /// ``` /// /// Returns `false` because the template text contains no line break. /// /// ```javascript /// "test" + /// `template /// with line break`; /// ``` /// /// Returns `false` because the template isn't on the same line as the '+' token. pub(crate) fn is_multiline_template_starting_on_same_line(template: &JsTemplateExpression) -> bool { let contains_new_line = template_literal_contains_new_line(template); let starts_on_same_line = template.syntax().first_token().map_or(false, |token| { for piece in token.leading_trivia().pieces() { if let Some(comment) = piece.as_comments() { if comment.has_newline() { return false; } } else if piece.is_newline() { return false; } } true }); contains_new_line && starts_on_same_line } #[cfg(test)] mod tests { use crate::{assert_needs_parentheses, assert_not_needs_parentheses}; use rome_js_syntax::{JsArrowFunctionExpression, JsFileSource}; #[test] fn needs_parentheses() { assert_needs_parentheses!("new (a => test)()`", JsArrowFunctionExpression); assert_needs_parentheses!("(a => test)()", JsArrowFunctionExpression); assert_needs_parentheses!("(a => test).member", JsArrowFunctionExpression); assert_needs_parentheses!("(a => test)[member]", JsArrowFunctionExpression); assert_not_needs_parentheses!("object[a => a]", JsArrowFunctionExpression); assert_needs_parentheses!("(a => a) as Function", JsArrowFunctionExpression); assert_needs_parentheses!("(a => a)!", JsArrowFunctionExpression); assert_needs_parentheses!("(a => a)`template`", JsArrowFunctionExpression); assert_needs_parentheses!("+(a => a)", JsArrowFunctionExpression); assert_needs_parentheses!("(a => a) && b", JsArrowFunctionExpression); assert_needs_parentheses!("(a => a) instanceof b", JsArrowFunctionExpression); assert_needs_parentheses!("(a => a) in b", JsArrowFunctionExpression); assert_needs_parentheses!("(a => a) + b", JsArrowFunctionExpression); assert_needs_parentheses!("await (a => a)", JsArrowFunctionExpression); assert_needs_parentheses!( "<Function>(a => a)", JsArrowFunctionExpression, JsFileSource::ts() ); assert_needs_parentheses!("(a => a) ? b : c", JsArrowFunctionExpression); assert_not_needs_parentheses!("a ? b => b : c", JsArrowFunctionExpression); assert_not_needs_parentheses!("a ? b : c => c", JsArrowFunctionExpression); assert_needs_parentheses!("class Test extends (a => a) {}", JsArrowFunctionExpression); } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/module/import_bare_clause.rs
crates/rome_js_formatter/src/js/module/import_bare_clause.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::JsImportBareClause; use rome_js_syntax::JsImportBareClauseFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsImportBareClause; impl FormatNodeRule<JsImportBareClause> for FormatJsImportBareClause { fn fmt_fields(&self, node: &JsImportBareClause, f: &mut JsFormatter) -> FormatResult<()> { let JsImportBareClauseFields { source, assertion } = node.as_fields(); write!(f, [source.format()])?; if let Some(assertion) = assertion { write!(f, [space(), assertion.format()])?; } Ok(()) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/module/export_as_clause.rs
crates/rome_js_formatter/src/js/module/export_as_clause.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::JsExportAsClause; use rome_js_syntax::JsExportAsClauseFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsExportAsClause; impl FormatNodeRule<JsExportAsClause> for FormatJsExportAsClause { fn fmt_fields(&self, node: &JsExportAsClause, f: &mut JsFormatter) -> FormatResult<()> { let JsExportAsClauseFields { as_token, exported_name, } = node.as_fields(); write![f, [as_token.format(), space(), exported_name.format()]] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/module/export_named_from_clause.rs
crates/rome_js_formatter/src/js/module/export_named_from_clause.rs
use crate::prelude::*; use crate::utils::FormatStatementSemicolon; use rome_formatter::write; use rome_js_syntax::JsExportNamedFromClause; use rome_js_syntax::JsExportNamedFromClauseFields; use rome_rowan::{AstNode, AstSeparatedElement}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsExportNamedFromClause; impl FormatNodeRule<JsExportNamedFromClause> for FormatJsExportNamedFromClause { fn fmt_fields(&self, node: &JsExportNamedFromClause, f: &mut JsFormatter) -> FormatResult<()> { let JsExportNamedFromClauseFields { type_token, l_curly_token, specifiers, r_curly_token, from_token, source, assertion, semicolon_token, } = node.as_fields(); if let Some(type_token) = &type_token { write!(f, [type_token.format(), space()])?; } write!(f, [l_curly_token.format(),])?; match specifiers.elements().next() { Some(AstSeparatedElement { node: Ok(node), trailing_separator: Ok(separator), }) if specifiers.len() == 1 && !f.comments().has_comments(node.syntax()) => { write!(f, [space(), node.format()])?; if let Some(separator) = separator { write!(f, [format_removed(&separator)])?; } write!(f, [space()])?; } _ => { if specifiers.syntax().has_leading_newline() { write!(f, [block_indent(&specifiers.format()),])?; } else { write!( f, [group(&soft_space_or_block_indent(&specifiers.format())),] )?; }; } } write![ f, [ r_curly_token.format(), space(), from_token.format(), space(), source.format(), ] ]?; if let Some(assertion) = &assertion { write!(f, [space(), assertion.format()])?; } write!(f, [FormatStatementSemicolon::new(semicolon_token.as_ref())]) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/module/export_named_clause.rs
crates/rome_js_formatter/src/js/module/export_named_clause.rs
use crate::prelude::*; use rome_formatter::{format_args, write}; use crate::utils::FormatStatementSemicolon; use rome_js_syntax::JsExportNamedClause; use rome_js_syntax::JsExportNamedClauseFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsExportNamedClause; impl FormatNodeRule<JsExportNamedClause> for FormatJsExportNamedClause { fn fmt_fields(&self, node: &JsExportNamedClause, f: &mut JsFormatter) -> FormatResult<()> { let JsExportNamedClauseFields { type_token, l_curly_token, specifiers, r_curly_token, semicolon_token, } = node.as_fields(); if let Some(type_token) = &type_token { write!(f, [type_token.format(), space()])?; } write!(f, [l_curly_token.format()])?; if specifiers.is_empty() { write!( f, [format_dangling_comments(node.syntax()).with_block_indent()] )?; } else { write!( f, [group(&format_args![ soft_line_indent_or_space(&specifiers.format()), soft_line_break_or_space(), ])] )?; } write!( f, [ r_curly_token.format(), FormatStatementSemicolon::new(semicolon_token.as_ref()) ] ) } fn fmt_dangling_comments( &self, _: &JsExportNamedClause, _: &mut JsFormatter, ) -> FormatResult<()> { // Handled as part of `fmt_fields` Ok(()) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/module/named_import_specifier.rs
crates/rome_js_formatter/src/js/module/named_import_specifier.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::JsNamedImportSpecifier; use rome_js_syntax::JsNamedImportSpecifierFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsNamedImportSpecifier; impl FormatNodeRule<JsNamedImportSpecifier> for FormatJsNamedImportSpecifier { fn fmt_fields(&self, node: &JsNamedImportSpecifier, f: &mut JsFormatter) -> FormatResult<()> { let JsNamedImportSpecifierFields { type_token, name, as_token, local_name, } = node.as_fields(); if let Some(type_token) = type_token { write!(f, [type_token.format(), space()])?; } write![ f, [ name.format(), space(), as_token.format(), space(), local_name.format() ] ] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/module/import_namespace_clause.rs
crates/rome_js_formatter/src/js/module/import_namespace_clause.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::JsImportNamespaceClause; use rome_js_syntax::JsImportNamespaceClauseFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsImportNamespaceClause; impl FormatNodeRule<JsImportNamespaceClause> for FormatJsImportNamespaceClause { fn fmt_fields(&self, node: &JsImportNamespaceClause, f: &mut JsFormatter) -> FormatResult<()> { let JsImportNamespaceClauseFields { type_token, star_token, as_token, local_name, from_token, source, assertion, } = node.as_fields(); if let Some(type_token) = type_token { write!(f, [type_token.format(), space()])?; } write![ f, [ star_token.format(), space(), as_token.format(), space(), local_name.format(), space(), from_token.format(), space(), source.format(), ] ]?; if let Some(assertion) = assertion { write!(f, [space(), assertion.format()])?; } Ok(()) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/module/export_default_expression_clause.rs
crates/rome_js_formatter/src/js/module/export_default_expression_clause.rs
use crate::prelude::*; use rome_formatter::write; use crate::utils::FormatStatementSemicolon; use rome_js_syntax::JsExportDefaultExpressionClause; use rome_js_syntax::JsExportDefaultExpressionClauseFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsExportDefaultExpressionClause; impl FormatNodeRule<JsExportDefaultExpressionClause> for FormatJsExportDefaultExpressionClause { fn fmt_fields( &self, node: &JsExportDefaultExpressionClause, f: &mut JsFormatter, ) -> FormatResult<()> { let JsExportDefaultExpressionClauseFields { default_token, expression, semicolon_token, } = node.as_fields(); write!( f, [ default_token.format(), space(), expression.format(), FormatStatementSemicolon::new(semicolon_token.as_ref()) ] ) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/module/export_named_specifier.rs
crates/rome_js_formatter/src/js/module/export_named_specifier.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::JsExportNamedSpecifier; use rome_js_syntax::JsExportNamedSpecifierFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsExportNamedSpecifier; impl FormatNodeRule<JsExportNamedSpecifier> for FormatJsExportNamedSpecifier { fn fmt_fields(&self, node: &JsExportNamedSpecifier, f: &mut JsFormatter) -> FormatResult<()> { let JsExportNamedSpecifierFields { type_token, local_name, as_token, exported_name, } = node.as_fields(); if let Some(type_token) = type_token { write!(f, [type_token.format(), space()])?; } write![ f, [ local_name.format(), space(), as_token.format(), space(), exported_name.format() ] ] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/module/namespace_import_specifier.rs
crates/rome_js_formatter/src/js/module/namespace_import_specifier.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::JsNamespaceImportSpecifier; use rome_js_syntax::JsNamespaceImportSpecifierFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsNamespaceImportSpecifier; impl FormatNodeRule<JsNamespaceImportSpecifier> for FormatJsNamespaceImportSpecifier { fn fmt_fields( &self, node: &JsNamespaceImportSpecifier, f: &mut JsFormatter, ) -> FormatResult<()> { let JsNamespaceImportSpecifierFields { star_token, as_token, local_name, } = node.as_fields(); write![ f, [ star_token.format(), space(), as_token.format(), space(), local_name.format() ] ] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/module/named_import_specifiers.rs
crates/rome_js_formatter/src/js/module/named_import_specifiers.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::JsNamedImportSpecifiers; use rome_js_syntax::JsNamedImportSpecifiersFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsNamedImportSpecifiers; impl FormatNodeRule<JsNamedImportSpecifiers> for FormatJsNamedImportSpecifiers { fn fmt_fields(&self, node: &JsNamedImportSpecifiers, f: &mut JsFormatter) -> FormatResult<()> { let JsNamedImportSpecifiersFields { l_curly_token, specifiers, r_curly_token, } = node.as_fields(); write!(f, [l_curly_token.format()])?; if specifiers.is_empty() { write!( f, [format_dangling_comments(node.syntax()).with_soft_block_indent()] )?; } else { write!( f, [group(&soft_space_or_block_indent(&specifiers.format()))] )?; } write!(f, [r_curly_token.format()]) } fn fmt_dangling_comments( &self, _: &JsNamedImportSpecifiers, _: &mut JsFormatter, ) -> FormatResult<()> { // Handled inside of `fmt_fields` Ok(()) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/module/default_import_specifier.rs
crates/rome_js_formatter/src/js/module/default_import_specifier.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::JsDefaultImportSpecifier; use rome_js_syntax::JsDefaultImportSpecifierFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsDefaultImportSpecifier; impl FormatNodeRule<JsDefaultImportSpecifier> for FormatJsDefaultImportSpecifier { fn fmt_fields(&self, node: &JsDefaultImportSpecifier, f: &mut JsFormatter) -> FormatResult<()> { let JsDefaultImportSpecifierFields { local_name, trailing_comma_token, } = node.as_fields(); write![f, [local_name.format(), trailing_comma_token.format()]] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/module/export_default_declaration_clause.rs
crates/rome_js_formatter/src/js/module/export_default_declaration_clause.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::{JsExportDefaultDeclarationClause, JsExportDefaultDeclarationClauseFields}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsExportDefaultDeclarationClause; impl FormatNodeRule<JsExportDefaultDeclarationClause> for FormatJsExportDefaultDeclarationClause { fn fmt_fields( &self, node: &JsExportDefaultDeclarationClause, f: &mut JsFormatter, ) -> FormatResult<()> { let JsExportDefaultDeclarationClauseFields { default_token, declaration, semicolon_token: _, } = node.as_fields(); write![f, [default_token.format(), space(), declaration.format()]] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/module/mod.rs
crates/rome_js_formatter/src/js/module/mod.rs
//! This is a generated file. Don't modify it by hand! Run 'cargo codegen formatter' to re-generate the file. pub(crate) mod default_import_specifier; pub(crate) mod export; pub(crate) mod export_as_clause; pub(crate) mod export_default_declaration_clause; pub(crate) mod export_default_expression_clause; pub(crate) mod export_from_clause; pub(crate) mod export_named_clause; pub(crate) mod export_named_from_clause; pub(crate) mod export_named_from_specifier; pub(crate) mod export_named_shorthand_specifier; pub(crate) mod export_named_specifier; pub(crate) mod import; pub(crate) mod import_assertion; pub(crate) mod import_assertion_entry; pub(crate) mod import_bare_clause; pub(crate) mod import_default_clause; pub(crate) mod import_named_clause; pub(crate) mod import_namespace_clause; pub(crate) mod literal_export_name; pub(crate) mod module_source; pub(crate) mod named_import_specifier; pub(crate) mod named_import_specifiers; pub(crate) mod namespace_import_specifier; pub(crate) mod shorthand_named_import_specifier;
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/module/import_default_clause.rs
crates/rome_js_formatter/src/js/module/import_default_clause.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::JsImportDefaultClause; use rome_js_syntax::JsImportDefaultClauseFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsImportDefaultClause; impl FormatNodeRule<JsImportDefaultClause> for FormatJsImportDefaultClause { fn fmt_fields(&self, node: &JsImportDefaultClause, f: &mut JsFormatter) -> FormatResult<()> { let JsImportDefaultClauseFields { type_token, local_name, from_token, source, assertion, } = node.as_fields(); if let Some(type_token) = type_token { write!(f, [type_token.format(), space()])?; } write![ f, [ local_name.format(), space(), from_token.format(), space(), source.format(), ] ]?; if let Some(assertion) = assertion { write!(f, [space(), assertion.format()])?; } Ok(()) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/module/literal_export_name.rs
crates/rome_js_formatter/src/js/module/literal_export_name.rs
use crate::prelude::*; use crate::utils::{FormatLiteralStringToken, StringLiteralParentKind}; use rome_js_syntax::JsLiteralExportName; use rome_js_syntax::JsLiteralExportNameFields; use rome_js_syntax::JsSyntaxKind::JS_STRING_LITERAL; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsLiteralExportName; impl FormatNodeRule<JsLiteralExportName> for FormatJsLiteralExportName { fn fmt_fields(&self, node: &JsLiteralExportName, f: &mut JsFormatter) -> FormatResult<()> { let JsLiteralExportNameFields { value } = node.as_fields(); let value = value?; if value.kind() == JS_STRING_LITERAL { FormatLiteralStringToken::new(&value, StringLiteralParentKind::Expression).fmt(f) } else { value.format().fmt(f) } } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/module/module_source.rs
crates/rome_js_formatter/src/js/module/module_source.rs
use crate::prelude::*; use crate::utils::{FormatLiteralStringToken, StringLiteralParentKind}; use rome_formatter::write; use rome_js_syntax::JsModuleSource; use rome_js_syntax::JsModuleSourceFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsModuleSource; impl FormatNodeRule<JsModuleSource> for FormatJsModuleSource { fn fmt_fields(&self, node: &JsModuleSource, f: &mut JsFormatter) -> FormatResult<()> { let JsModuleSourceFields { value_token } = node.as_fields(); write!( f, [FormatLiteralStringToken::new( &value_token?, StringLiteralParentKind::Expression )] ) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/module/export.rs
crates/rome_js_formatter/src/js/module/export.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::JsExport; use rome_js_syntax::JsExportFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsExport; impl FormatNodeRule<JsExport> for FormatJsExport { fn fmt_fields(&self, node: &JsExport, f: &mut JsFormatter) -> FormatResult<()> { let JsExportFields { decorators, export_token, export_clause, } = node.as_fields(); write![ f, [ decorators.format(), export_token.format(), space(), export_clause.format() ] ] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/module/import.rs
crates/rome_js_formatter/src/js/module/import.rs
use crate::prelude::*; use rome_formatter::write; use crate::utils::FormatStatementSemicolon; use rome_js_syntax::JsImport; use rome_js_syntax::JsImportFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsImport; impl FormatNodeRule<JsImport> for FormatJsImport { fn fmt_fields(&self, node: &JsImport, f: &mut JsFormatter) -> FormatResult<()> { let JsImportFields { import_token, import_clause, semicolon_token, } = node.as_fields(); write!( f, [ import_token.format(), space(), import_clause.format(), FormatStatementSemicolon::new(semicolon_token.as_ref()) ] ) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/module/export_from_clause.rs
crates/rome_js_formatter/src/js/module/export_from_clause.rs
use crate::prelude::*; use rome_formatter::write; use crate::utils::FormatStatementSemicolon; use rome_js_syntax::JsExportFromClause; use rome_js_syntax::JsExportFromClauseFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsExportFromClause; impl FormatNodeRule<JsExportFromClause> for FormatJsExportFromClause { fn fmt_fields(&self, node: &JsExportFromClause, f: &mut JsFormatter) -> FormatResult<()> { let JsExportFromClauseFields { type_token, star_token, export_as, from_token, source, assertion, semicolon_token, } = node.as_fields(); if let Some(type_token) = type_token { write!(f, [type_token.format(), space()])?; } write!(f, [star_token.format(), space(),])?; if let Some(export_as) = export_as { write!(f, [export_as.format(), space()])?; } write!(f, [from_token.format(), space(), source.format()])?; if let Some(assertion) = assertion { write!(f, [space(), assertion.format()])?; } FormatStatementSemicolon::new(semicolon_token.as_ref()).fmt(f) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/module/import_named_clause.rs
crates/rome_js_formatter/src/js/module/import_named_clause.rs
use crate::prelude::*; use rome_formatter::{write, CstFormatContext}; use rome_js_syntax::AnyJsNamedImport; use rome_js_syntax::AnyJsNamedImportSpecifier; use rome_js_syntax::JsImportNamedClause; use rome_js_syntax::JsImportNamedClauseFields; use rome_js_syntax::JsNamedImportSpecifiersFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsImportNamedClause; impl FormatNodeRule<JsImportNamedClause> for FormatJsImportNamedClause { fn fmt_fields(&self, node: &JsImportNamedClause, f: &mut JsFormatter) -> FormatResult<()> { let JsImportNamedClauseFields { type_token, default_specifier, named_import, from_token, source, assertion, } = node.as_fields(); if let Some(type_token) = type_token { write!(f, [type_token.format(), space()])?; } let is_default_specifier_empty = default_specifier.is_none(); if let Some(default_specifier) = default_specifier { write!(f, [default_specifier.format(), space()])?; } let named_import = named_import?; // can_break implementation, return `format_element` instead of boolean to reduce enum conversion overhead. // if `can_break` is true we just use the previous format strategy, otherwise we use the new format strategy. // reference https://github.com/prettier/prettier/blob/5b113e71b1808d6916f446c3aa49c3c53e3bdb98/src/language-js/print/module.js#L173 // https://github.com/prettier/prettier/blob/5b113e71b1808d6916f446c3aa49c3c53e3bdb98/src/language-js/print/module.js#L184-L209v, // `standaloneSpecifiers` corresponding our `JsDefaultImportSpecifier` + part of `JsNamespaceImportSpecifier`, // `groupedSpecifiers` corresponding our `JsNamedImportSpecifiers` // Here we use an opposite way of thinking, we only thinking about the way that can not break // That's to say // 1. `default_specifier` need to be none. // 2. length of `JsNamedImportSpecifiers` at least is one // 3. Surrounding of the only `JsNamedImportSpecifiers` should not have any comments if !is_default_specifier_empty { // `can_break` is true. write![f, [named_import.format()]] } else { match named_import { AnyJsNamedImport::JsNamedImportSpecifiers(ref specifiers) if specifiers.specifiers().len() == 1 && !f.context().comments().is_suppressed(specifiers.syntax()) => { // SAFETY: we know that the `specifiers.specifiers().len() == 1`, so unwrap `iter().next()` is safe. let first_specifier = specifiers.specifiers().elements().next().unwrap(); match (first_specifier.node(), first_specifier.trailing_separator()) { ( Ok(AnyJsNamedImportSpecifier::JsShorthandNamedImportSpecifier( specifier, )), Ok(separator), ) => { if f.comments().has_comments(specifier.syntax()) { write!(f, [named_import.format()]) } else { let JsNamedImportSpecifiersFields { l_curly_token, specifiers: _, r_curly_token, } = specifiers.as_fields(); write!(f, [l_curly_token.format(), space(), specifier.format(),])?; if let Some(separator) = separator { format_removed(separator).fmt(f)?; } write!(f, [space(), r_curly_token.format()]) } } ( Ok(AnyJsNamedImportSpecifier::JsNamedImportSpecifier(specifier)), Ok(separator), ) => { if f.comments().has_comments(specifier.syntax()) { write!(f, [named_import.format()]) } else { let JsNamedImportSpecifiersFields { l_curly_token, specifiers: _, r_curly_token, } = specifiers.as_fields(); write!(f, [l_curly_token.format(), space(), specifier.format(),])?; if let Some(separator) = separator { format_removed(separator).fmt(f)?; } write!(f, [space(), r_curly_token.format()]) } } _ => write![f, [named_import.format()]], } } _ => write![f, [named_import.format()]], } }?; write![f, [space(), from_token.format(), space(), source.format(),]]?; if let Some(assertion) = assertion { write!(f, [space(), assertion.format()])?; } Ok(()) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/module/import_assertion.rs
crates/rome_js_formatter/src/js/module/import_assertion.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::JsImportAssertion; use rome_js_syntax::JsImportAssertionFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsImportAssertion; impl FormatNodeRule<JsImportAssertion> for FormatJsImportAssertion { fn fmt_fields(&self, node: &JsImportAssertion, f: &mut JsFormatter) -> FormatResult<()> { let JsImportAssertionFields { l_curly_token, assertions, r_curly_token, assertion_kind, } = node.as_fields(); write![ f, [assertion_kind.format(), space(), l_curly_token.format()] ]?; if assertions.is_empty() { let has_dangling = f.comments().has_dangling_comments(node.syntax()); write!( f, [ has_dangling.then_some(space()), format_dangling_comments(node.syntax()).with_soft_block_indent(), has_dangling.then_some(space()), ] )?; } else { write!( f, [group(&soft_space_or_block_indent(&assertions.format()))] )?; } write!(f, [r_curly_token.format()]) } fn fmt_dangling_comments( &self, _: &JsImportAssertion, _: &mut JsFormatter, ) -> FormatResult<()> { // Handled as part of `fmt_fields` Ok(()) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/module/shorthand_named_import_specifier.rs
crates/rome_js_formatter/src/js/module/shorthand_named_import_specifier.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::JsShorthandNamedImportSpecifier; use rome_js_syntax::JsShorthandNamedImportSpecifierFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsShorthandNamedImportSpecifier; impl FormatNodeRule<JsShorthandNamedImportSpecifier> for FormatJsShorthandNamedImportSpecifier { fn fmt_fields( &self, node: &JsShorthandNamedImportSpecifier, f: &mut JsFormatter, ) -> FormatResult<()> { let JsShorthandNamedImportSpecifierFields { type_token, local_name, } = node.as_fields(); if let Some(type_token) = type_token { write!(f, [type_token.format(), space()])?; } write![f, [local_name.format()]] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/module/export_named_shorthand_specifier.rs
crates/rome_js_formatter/src/js/module/export_named_shorthand_specifier.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::JsExportNamedShorthandSpecifier; use rome_js_syntax::JsExportNamedShorthandSpecifierFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsExportNamedShorthandSpecifier; impl FormatNodeRule<JsExportNamedShorthandSpecifier> for FormatJsExportNamedShorthandSpecifier { fn fmt_fields( &self, node: &JsExportNamedShorthandSpecifier, f: &mut JsFormatter, ) -> FormatResult<()> { let JsExportNamedShorthandSpecifierFields { type_token, name } = node.as_fields(); if let Some(type_token) = type_token { write!(f, [type_token.format(), space()])?; } write![f, [name.format()]] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/module/import_assertion_entry.rs
crates/rome_js_formatter/src/js/module/import_assertion_entry.rs
use crate::prelude::*; use rome_formatter::write; use crate::utils::{FormatLiteralStringToken, StringLiteralParentKind}; use rome_js_syntax::JsImportAssertionEntryFields; use rome_js_syntax::{JsImportAssertionEntry, JsSyntaxKind}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsImportAssertionEntry; impl FormatNodeRule<JsImportAssertionEntry> for FormatJsImportAssertionEntry { fn fmt_fields(&self, node: &JsImportAssertionEntry, f: &mut JsFormatter) -> FormatResult<()> { let JsImportAssertionEntryFields { key, colon_token, value_token, } = node.as_fields(); let key = key?; match key.kind() { JsSyntaxKind::JS_STRING_LITERAL => { write!( f, [FormatLiteralStringToken::new( &key, StringLiteralParentKind::Expression )] )?; } _ => { write![f, [key.format()]]?; } }; write![f, [colon_token.format(), space()]]?; if f.comments().has_dangling_comments(node.syntax()) { write!( f, [space(), format_dangling_comments(node.syntax()), space()] )?; } write!( f, [FormatLiteralStringToken::new( &value_token?, StringLiteralParentKind::Expression )] ) } fn fmt_dangling_comments( &self, _: &JsImportAssertionEntry, _: &mut JsFormatter, ) -> FormatResult<()> { // Handled inside `fmt_fields` Ok(()) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/module/export_named_from_specifier.rs
crates/rome_js_formatter/src/js/module/export_named_from_specifier.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::JsExportNamedFromSpecifier; use rome_js_syntax::JsExportNamedFromSpecifierFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsExportNamedFromSpecifier; impl FormatNodeRule<JsExportNamedFromSpecifier> for FormatJsExportNamedFromSpecifier { fn fmt_fields( &self, node: &JsExportNamedFromSpecifier, f: &mut JsFormatter, ) -> FormatResult<()> { let JsExportNamedFromSpecifierFields { type_token, source_name, export_as, } = node.as_fields(); if let Some(type_token) = type_token { write!(f, [type_token.format(), space()])?; } write!(f, [source_name.format()])?; if let Some(export_as) = export_as { write!(f, [space(), export_as.format()])?; } Ok(()) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/classes/setter_class_member.rs
crates/rome_js_formatter/src/js/classes/setter_class_member.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::JsSetterClassMember; use rome_js_syntax::JsSetterClassMemberFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsSetterClassMember; impl FormatNodeRule<JsSetterClassMember> for FormatJsSetterClassMember { fn fmt_fields(&self, node: &JsSetterClassMember, f: &mut JsFormatter) -> FormatResult<()> { let JsSetterClassMemberFields { modifiers, set_token, name, l_paren_token, parameter, r_paren_token, body, } = node.as_fields(); write![ f, [ modifiers.format(), space(), set_token.format(), space(), name.format(), l_paren_token.format(), parameter.format(), r_paren_token.format(), space(), body.format(), ] ] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/classes/property_class_member.rs
crates/rome_js_formatter/src/js/classes/property_class_member.rs
use crate::context::Semicolons; use crate::prelude::*; use crate::utils::{AnyJsAssignmentLike, FormatSemicolon}; use rome_formatter::write; use rome_js_syntax::{ AnyJsClassMember, AnyJsClassMemberName, JsInitializerClause, JsPropertyClassMember, JsSyntaxToken, TsInitializedPropertySignatureClassMember, TsPropertySignatureClassMember, }; use rome_rowan::{declare_node_union, SyntaxResult}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsPropertyClassMember; impl FormatNodeRule<JsPropertyClassMember> for FormatJsPropertyClassMember { fn fmt_fields(&self, node: &JsPropertyClassMember, f: &mut JsFormatter) -> FormatResult<()> { let semicolon_token = node.semicolon_token(); write!( f, [ &AnyJsAssignmentLike::from(node.clone()), FormatClassPropertySemicolon { semicolon: semicolon_token.as_ref(), property: &AnyJsPropertyClassMember::from(node.clone()) } ] ) } } declare_node_union! { pub(crate) AnyJsPropertyClassMember = JsPropertyClassMember | TsPropertySignatureClassMember | TsInitializedPropertySignatureClassMember } impl AnyJsPropertyClassMember { fn name(&self) -> SyntaxResult<AnyJsClassMemberName> { match self { AnyJsPropertyClassMember::JsPropertyClassMember(property) => property.name(), AnyJsPropertyClassMember::TsPropertySignatureClassMember(property) => property.name(), AnyJsPropertyClassMember::TsInitializedPropertySignatureClassMember(property) => { property.name() } } } fn value(&self) -> Option<JsInitializerClause> { match self { AnyJsPropertyClassMember::JsPropertyClassMember(property) => property.value(), AnyJsPropertyClassMember::TsPropertySignatureClassMember(_) => None, AnyJsPropertyClassMember::TsInitializedPropertySignatureClassMember(property) => { property.value().ok() } } } fn has_property_annotation(&self) -> bool { match self { AnyJsPropertyClassMember::JsPropertyClassMember(property) => { property.property_annotation().is_some() } AnyJsPropertyClassMember::TsPropertySignatureClassMember(property) => { property.property_annotation().is_some() } AnyJsPropertyClassMember::TsInitializedPropertySignatureClassMember(_) => false, } } } pub(crate) struct FormatClassPropertySemicolon<'a> { property: &'a AnyJsPropertyClassMember, semicolon: Option<&'a JsSyntaxToken>, } impl<'a> FormatClassPropertySemicolon<'a> { pub fn new( property: &'a AnyJsPropertyClassMember, semicolon: Option<&'a JsSyntaxToken>, ) -> Self { Self { property, semicolon, } } } impl Format<JsFormatContext> for FormatClassPropertySemicolon<'_> { fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> { match f.options().semicolons() { Semicolons::Always => FormatSemicolon::new(self.semicolon).fmt(f), Semicolons::AsNeeded => match (self.semicolon, needs_semicolon(self.property)?) { (None, false) => Ok(()), (Some(semicolon), true) => semicolon.format().fmt(f), (Some(semicolon), false) => format_removed(semicolon).fmt(f), (None, true) => FormatSemicolon::new(self.semicolon).fmt(f), }, } } } fn needs_semicolon(property: &AnyJsPropertyClassMember) -> SyntaxResult<bool> { if let AnyJsClassMemberName::JsLiteralMemberName(name) = property.name()? { // `get;`, `set;` or `static` if matches!(name.value()?.text_trimmed(), "static" | "get" | "set") && property.value().is_none() && !property.has_property_annotation() { return Ok(true); } } let Some(next_member) = property.syntax().next_sibling().and_then(AnyJsClassMember::cast) else { return Ok(false); }; // a; // static b; if has_modifiers(&next_member) { return Ok(false); } // a = b; // instanceof; if property.value().is_some() && (next_member.has_name("instanceof")? || next_member.has_name("in")?) { return Ok(true); } Ok(match next_member { AnyJsClassMember::TsConstructorSignatureClassMember(_) | AnyJsClassMember::JsConstructorClassMember(_) | AnyJsClassMember::JsEmptyClassMember(_) // `get`, `set`, and `static` start with a keyword -> no need for semi | AnyJsClassMember::JsStaticInitializationBlockClassMember(_) | AnyJsClassMember::JsGetterClassMember(_) | AnyJsClassMember::TsGetterSignatureClassMember(_) | AnyJsClassMember::TsSetterSignatureClassMember(_) | AnyJsClassMember::JsSetterClassMember(_) => false, // Computed members may be misinterpreted as array accessors/array types member @ AnyJsClassMember::JsPropertyClassMember(_) | member @ AnyJsClassMember::TsPropertySignatureClassMember(_) | member @ AnyJsClassMember::TsInitializedPropertySignatureClassMember(_) => match member.name()? { Some(name) => name.is_computed(), None => false, }, // When the name starts with the generator token or `[` AnyJsClassMember::JsMethodClassMember(method) => { method.async_token().is_none() && (method.name()?.is_computed() || method.star_token().is_some()) } // When the name starts with a `[` AnyJsClassMember::TsMethodSignatureClassMember(method) => { method.async_token().is_none() && method.name()?.is_computed() } // Keep it, just to be safe AnyJsClassMember::JsBogusMember(_) => true, AnyJsClassMember::TsIndexSignatureClassMember(_) => true, }) } /// Tests if `member` has any modifiers fn has_modifiers(member: &AnyJsClassMember) -> bool { let is_empty = match member { AnyJsClassMember::JsConstructorClassMember(constructor) => { constructor.modifiers().is_empty() } AnyJsClassMember::JsEmptyClassMember(_) => true, AnyJsClassMember::JsGetterClassMember(getter) => getter.modifiers().is_empty(), AnyJsClassMember::JsMethodClassMember(method) => method.modifiers().is_empty(), AnyJsClassMember::JsPropertyClassMember(property) => property.modifiers().is_empty(), AnyJsClassMember::JsSetterClassMember(setter) => setter.modifiers().is_empty(), AnyJsClassMember::JsStaticInitializationBlockClassMember(_) => true, AnyJsClassMember::JsBogusMember(_) => true, AnyJsClassMember::TsConstructorSignatureClassMember(constructor) => { constructor.modifiers().is_empty() } AnyJsClassMember::TsGetterSignatureClassMember(getter) => getter.modifiers().is_empty(), AnyJsClassMember::TsIndexSignatureClassMember(index) => index.modifiers().is_empty(), AnyJsClassMember::TsMethodSignatureClassMember(method) => method.modifiers().is_empty(), AnyJsClassMember::TsPropertySignatureClassMember(property) => { property.modifiers().is_empty() } AnyJsClassMember::TsInitializedPropertySignatureClassMember(property) => { property.modifiers().is_empty() } AnyJsClassMember::TsSetterSignatureClassMember(setter) => setter.modifiers().is_empty(), }; !is_empty }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/classes/empty_class_member.rs
crates/rome_js_formatter/src/js/classes/empty_class_member.rs
use crate::prelude::*; use rome_js_syntax::JsEmptyClassMember; use rome_js_syntax::JsEmptyClassMemberFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsEmptyClassMember; impl FormatNodeRule<JsEmptyClassMember> for FormatJsEmptyClassMember { fn fmt_fields(&self, node: &JsEmptyClassMember, f: &mut JsFormatter) -> FormatResult<()> { let JsEmptyClassMemberFields { semicolon_token } = node.as_fields(); format_removed(&semicolon_token?).fmt(f) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/classes/method_class_member.rs
crates/rome_js_formatter/src/js/classes/method_class_member.rs
use crate::prelude::*; use crate::js::declarations::function_declaration::should_group_function_parameters; use rome_formatter::write; use rome_js_syntax::{ AnyJsClassMemberName, AnyJsObjectMemberName, JsConstructorClassMember, JsConstructorParameters, JsFunctionBody, JsParameters, TsMethodSignatureClassMember, TsMethodSignatureTypeMember, TsReturnTypeAnnotation, TsTypeParameters, }; use rome_js_syntax::{JsMethodClassMember, JsMethodObjectMember, JsSyntaxToken}; use rome_rowan::{declare_node_union, SyntaxResult}; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsMethodClassMember; impl FormatNodeRule<JsMethodClassMember> for FormatJsMethodClassMember { fn fmt_fields(&self, node: &JsMethodClassMember, f: &mut JsFormatter) -> FormatResult<()> { write![ f, [ node.modifiers().format(), space(), FormatAnyJsMethodMember::from(node.clone()) ] ] } } declare_node_union! { /// Formats the type parameters, parameters, and return type annotation of a method pub(crate) FormatAnyJsMethodMember = JsMethodClassMember | JsMethodObjectMember | JsConstructorClassMember | TsMethodSignatureClassMember | TsMethodSignatureTypeMember } impl Format<JsFormatContext> for FormatAnyJsMethodMember { fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> { if let Some(async_token) = self.async_token() { write!(f, [async_token.format(), space()])?; } let type_parameters = self.type_parameters(); write!( f, [ self.star_token().format(), self.name(), self.question_mark_token().format(), type_parameters.format(), ] )?; write!( f, [group(&format_with(|f| { let parameters = self.parameters()?; let return_type_annotation = self.return_type_annotation(); let mut format_return_type_annotation = return_type_annotation.format().memoized(); if should_group_function_parameters( type_parameters.as_ref(), parameters.len(), return_type_annotation .as_ref() .map(|annotation| annotation.ty()), &mut format_return_type_annotation, f, )? { write!(f, [group(&parameters)])?; } else { write!(f, [parameters])?; } write!(f, [format_return_type_annotation]) }))] )?; if let Some(body) = self.body()? { write!(f, [space(), body.format()])?; } Ok(()) } } impl FormatAnyJsMethodMember { fn async_token(&self) -> Option<JsSyntaxToken> { match self { FormatAnyJsMethodMember::JsMethodClassMember(member) => member.async_token(), FormatAnyJsMethodMember::JsMethodObjectMember(member) => member.async_token(), FormatAnyJsMethodMember::JsConstructorClassMember(_) => None, FormatAnyJsMethodMember::TsMethodSignatureClassMember(signature) => { signature.async_token() } FormatAnyJsMethodMember::TsMethodSignatureTypeMember(_) => None, } } fn star_token(&self) -> Option<JsSyntaxToken> { match self { FormatAnyJsMethodMember::JsMethodClassMember(member) => member.star_token(), FormatAnyJsMethodMember::JsMethodObjectMember(member) => member.star_token(), FormatAnyJsMethodMember::JsConstructorClassMember(_) => None, FormatAnyJsMethodMember::TsMethodSignatureClassMember(_) => None, FormatAnyJsMethodMember::TsMethodSignatureTypeMember(_) => None, } } fn name(&self) -> SyntaxResult<AnyMemberName> { Ok(match self { FormatAnyJsMethodMember::JsMethodClassMember(member) => member.name()?.into(), FormatAnyJsMethodMember::JsMethodObjectMember(member) => member.name()?.into(), FormatAnyJsMethodMember::JsConstructorClassMember(member) => { AnyMemberName::from(AnyJsClassMemberName::from(member.name()?)) } FormatAnyJsMethodMember::TsMethodSignatureClassMember(signature) => { signature.name()?.into() } FormatAnyJsMethodMember::TsMethodSignatureTypeMember(member) => member.name()?.into(), }) } fn type_parameters(&self) -> Option<TsTypeParameters> { match self { FormatAnyJsMethodMember::JsMethodClassMember(member) => member.type_parameters(), FormatAnyJsMethodMember::JsMethodObjectMember(member) => member.type_parameters(), FormatAnyJsMethodMember::JsConstructorClassMember(_) => None, FormatAnyJsMethodMember::TsMethodSignatureClassMember(signature) => { signature.type_parameters() } FormatAnyJsMethodMember::TsMethodSignatureTypeMember(member) => { member.type_parameters() } } } fn parameters(&self) -> SyntaxResult<MethodParameters> { Ok(match self { FormatAnyJsMethodMember::JsMethodClassMember(member) => member.parameters()?.into(), FormatAnyJsMethodMember::JsMethodObjectMember(member) => member.parameters()?.into(), FormatAnyJsMethodMember::JsConstructorClassMember(member) => { member.parameters()?.into() } FormatAnyJsMethodMember::TsMethodSignatureClassMember(signature) => { signature.parameters()?.into() } FormatAnyJsMethodMember::TsMethodSignatureTypeMember(member) => { member.parameters()?.into() } }) } fn return_type_annotation(&self) -> Option<TsReturnTypeAnnotation> { match self { FormatAnyJsMethodMember::JsMethodClassMember(member) => member.return_type_annotation(), FormatAnyJsMethodMember::JsMethodObjectMember(member) => { member.return_type_annotation() } FormatAnyJsMethodMember::JsConstructorClassMember(_) => None, FormatAnyJsMethodMember::TsMethodSignatureClassMember(signature) => { signature.return_type_annotation() } FormatAnyJsMethodMember::TsMethodSignatureTypeMember(member) => { member.return_type_annotation() } } } fn question_mark_token(&self) -> Option<JsSyntaxToken> { match self { FormatAnyJsMethodMember::JsMethodClassMember(member) => member.question_mark_token(), FormatAnyJsMethodMember::JsMethodObjectMember(_) => None, FormatAnyJsMethodMember::JsConstructorClassMember(_) => None, FormatAnyJsMethodMember::TsMethodSignatureClassMember(signature) => { signature.question_mark_token() } FormatAnyJsMethodMember::TsMethodSignatureTypeMember(member) => member.optional_token(), } } fn body(&self) -> SyntaxResult<Option<JsFunctionBody>> { Ok(match self { FormatAnyJsMethodMember::JsMethodClassMember(member) => Some(member.body()?), FormatAnyJsMethodMember::JsMethodObjectMember(member) => Some(member.body()?), FormatAnyJsMethodMember::JsConstructorClassMember(member) => Some(member.body()?), FormatAnyJsMethodMember::TsMethodSignatureClassMember(_) => None, FormatAnyJsMethodMember::TsMethodSignatureTypeMember(_) => None, }) } } declare_node_union! { AnyMemberName = AnyJsClassMemberName | AnyJsObjectMemberName } impl Format<JsFormatContext> for AnyMemberName { fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> { match self { AnyMemberName::AnyJsClassMemberName(name) => name.format().fmt(f), AnyMemberName::AnyJsObjectMemberName(name) => name.format().fmt(f), } } } declare_node_union! { MethodParameters = JsParameters | JsConstructorParameters } impl MethodParameters { pub fn len(&self) -> usize { match self { MethodParameters::JsParameters(parameters) => parameters.items().len(), MethodParameters::JsConstructorParameters(parameters) => parameters.parameters().len(), } } } impl Format<JsFormatContext> for MethodParameters { fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> { match self { MethodParameters::JsParameters(parameters) => parameters.format().fmt(f), MethodParameters::JsConstructorParameters(parameters) => parameters.format().fmt(f), } } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/classes/mod.rs
crates/rome_js_formatter/src/js/classes/mod.rs
//! This is a generated file. Don't modify it by hand! Run 'cargo codegen formatter' to re-generate the file. pub(crate) mod constructor_class_member; pub(crate) mod empty_class_member; pub(crate) mod extends_clause; pub(crate) mod getter_class_member; pub(crate) mod method_class_member; pub(crate) mod property_class_member; pub(crate) mod setter_class_member; pub(crate) mod static_initialization_block_class_member;
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/classes/getter_class_member.rs
crates/rome_js_formatter/src/js/classes/getter_class_member.rs
use crate::prelude::*; use rome_formatter::write; use rome_js_syntax::JsGetterClassMember; use rome_js_syntax::JsGetterClassMemberFields; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsGetterClassMember; impl FormatNodeRule<JsGetterClassMember> for FormatJsGetterClassMember { fn fmt_fields(&self, node: &JsGetterClassMember, f: &mut JsFormatter) -> FormatResult<()> { let JsGetterClassMemberFields { modifiers, get_token, name, l_paren_token, r_paren_token, return_type, body, } = node.as_fields(); write![ f, [ modifiers.format(), space(), get_token.format(), space(), name.format(), l_paren_token.format(), r_paren_token.format(), return_type.format(), space(), body.format() ] ] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/js/classes/extends_clause.rs
crates/rome_js_formatter/src/js/classes/extends_clause.rs
use crate::prelude::*; use rome_formatter::{format_args, write}; use rome_js_syntax::JsExtendsClause; use rome_js_syntax::JsExtendsClauseFields; use rome_js_syntax::JsSyntaxKind::JS_ASSIGNMENT_EXPRESSION; #[derive(Debug, Clone, Default)] pub(crate) struct FormatJsExtendsClause; impl FormatNodeRule<JsExtendsClause> for FormatJsExtendsClause { fn fmt_fields(&self, node: &JsExtendsClause, f: &mut JsFormatter) -> FormatResult<()> { let JsExtendsClauseFields { extends_token, super_class, type_arguments, } = node.as_fields(); let super_class = super_class?; let format_super = format_with(|f| { let content = format_with(|f| write!(f, [super_class.format(), type_arguments.format()])); let comments = f.comments(); let has_trailing_comments = if let Some(type_arguments) = &type_arguments { comments.has_trailing_comments(type_arguments.syntax()) } else { comments.has_trailing_comments(super_class.syntax()) }; if node .syntax() .grand_parent() .map_or(false, |p| p.kind() == JS_ASSIGNMENT_EXPRESSION) { if comments.has_leading_comments(super_class.syntax()) || has_trailing_comments { write!(f, [text("("), &content, text(")")]) } else { let content = content.memoized(); write!( f, [ if_group_breaks(&format_args![ text("("), &soft_block_indent(&content), text(")"), ]), if_group_fits_on_line(&content) ] ) } } else { content.fmt(f) } }); write![f, [extends_token.format(), space(), group(&format_super)]] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false