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/utils/typescript.rs | crates/rome_js_formatter/src/utils/typescript.rs | use rome_js_syntax::{
AnyTsType, JsSyntaxKind, JsSyntaxNode, TsIntersectionTypeElementList, TsUnionTypeVariantList,
};
use rome_rowan::AstSeparatedList;
use crate::parentheses::{
is_in_many_type_union_or_intersection_list, operator_type_or_higher_needs_parens,
};
/// Utility function that checks if the current type is object like type
/// ```ts
/// type A = {};
/// type B = {
/// [key in A]: number;
/// };
/// ```
pub(crate) fn is_object_like_type(ty: &AnyTsType) -> bool {
matches!(ty, AnyTsType::TsMappedType(_) | AnyTsType::TsObjectType(_))
}
/// Utility function that checks if the current type is can categorized as "simple"
pub(crate) fn is_simple_type(ty: &AnyTsType) -> bool {
if matches!(
ty,
AnyTsType::TsAnyType(_)
| AnyTsType::TsNullLiteralType(_)
| AnyTsType::TsThisType(_)
| AnyTsType::TsVoidType(_)
| AnyTsType::TsNumberType(_)
| AnyTsType::TsNumberLiteralType(_)
| AnyTsType::TsBooleanType(_)
| AnyTsType::TsBooleanLiteralType(_)
| AnyTsType::TsBigintType(_)
| AnyTsType::TsBigintLiteralType(_)
| AnyTsType::TsStringType(_)
| AnyTsType::TsStringLiteralType(_)
| AnyTsType::TsSymbolType(_)
| AnyTsType::TsTemplateLiteralType(_)
| AnyTsType::TsNeverType(_)
| AnyTsType::TsNonPrimitiveType(_)
| AnyTsType::TsUndefinedType(_)
| AnyTsType::TsUnknownType(_)
) {
return true;
}
if let AnyTsType::TsReferenceType(reference) = ty {
return reference.type_arguments().is_none();
}
false
}
/// Logic ported from [prettier], function `shouldHugType`
///
/// [prettier]: https://github.com/prettier/prettier/blob/main/src/language-js/print/type-annotation.js#L27-L56
pub(crate) fn should_hug_type(ty: &AnyTsType) -> bool {
if is_simple_type(ty) || is_object_like_type(ty) {
return true;
}
// Checking for unions where all types but one are "void types", so things like `TypeName | null | void`
if let AnyTsType::TsUnionType(union_type) = ty {
let mut iter = union_type.types().iter();
let has_object_type = iter.any(|ty| {
matches!(
ty,
Ok(AnyTsType::TsObjectType(_) | AnyTsType::TsReferenceType(_))
)
});
let void_count = union_type
.types()
.iter()
.filter(|node| {
matches!(
node,
Ok(AnyTsType::TsVoidType(_) | AnyTsType::TsNullLiteralType(_))
)
})
.count();
union_type.types().len() - 1 == void_count && has_object_type
} else {
false
}
}
pub(crate) fn union_or_intersection_type_needs_parentheses(
node: &JsSyntaxNode,
parent: &JsSyntaxNode,
types: &TsIntersectionOrUnionTypeList,
) -> bool {
debug_assert!(matches!(
node.kind(),
JsSyntaxKind::TS_INTERSECTION_TYPE | JsSyntaxKind::TS_UNION_TYPE
));
if is_in_many_type_union_or_intersection_list(node, parent) {
types.len() > 1
} else {
operator_type_or_higher_needs_parens(node, parent)
}
}
pub(crate) enum TsIntersectionOrUnionTypeList {
TsIntersectionTypeElementList(TsIntersectionTypeElementList),
TsUnionTypeVariantList(TsUnionTypeVariantList),
}
impl TsIntersectionOrUnionTypeList {
fn len(&self) -> usize {
match self {
TsIntersectionOrUnionTypeList::TsIntersectionTypeElementList(list) => list.len(),
TsIntersectionOrUnionTypeList::TsUnionTypeVariantList(list) => list.len(),
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/utils/function_body.rs | crates/rome_js_formatter/src/utils/function_body.rs | use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::AnyJsFunctionBody;
#[derive(Copy, Clone, Debug, Default)]
pub enum FunctionBodyCacheMode {
/// Format the body without caching it or retrieving it from the cache.
#[default]
NoCache,
/// The body has been cached before, try to retrieve the body from the cache.
Cached,
/// Cache the body during the next [formatting](Format::fmt).
Cache,
}
/// Formats a [function body](AnyJsFunctionBody) with additional caching depending on [`mode`](Self::mode).
pub(crate) struct FormatMaybeCachedFunctionBody<'a> {
/// The body to format.
pub body: &'a AnyJsFunctionBody,
/// If the body should be cached or if the formatter should try to retrieve it from the cache.
pub mode: FunctionBodyCacheMode,
}
impl Format<JsFormatContext> for FormatMaybeCachedFunctionBody<'_> {
fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
match self.mode {
FunctionBodyCacheMode::NoCache => {
write!(f, [self.body.format()])
}
FunctionBodyCacheMode::Cached => {
match f.context().get_cached_function_body(self.body) {
Some(cached) => f.write_element(cached),
None => {
// This can happen in the unlikely event where a function has a parameter with
// an initializer that contains a call expression with a first or last function/arrow
// ```javascript
// test((
// problematic = test(() => body)
// ) => {});
// ```
// This case should be rare as it requires very specific syntax (and is rather messy to write)
// which is why it's fine to just fallback to formatting the body again in this case.
write!(f, [self.body.format()])
}
}
}
FunctionBodyCacheMode::Cache => match f.intern(&self.body.format())? {
Some(interned) => {
f.context_mut()
.set_cached_function_body(self.body, interned.clone());
f.write_element(interned)
}
None => 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/utils/object_pattern_like.rs | crates/rome_js_formatter/src/utils/object_pattern_like.rs | use crate::js::bindings::parameters::{should_hug_function_parameters, FormatAnyJsParameters};
use crate::prelude::*;
use crate::JsFormatContext;
use rome_formatter::formatter::Formatter;
use rome_formatter::write;
use rome_formatter::{Format, FormatResult};
use rome_js_syntax::{
AnyJsAssignmentPattern, AnyJsBindingPattern, AnyJsFormalParameter,
AnyJsObjectAssignmentPatternMember, AnyJsObjectBindingPatternMember, JsObjectAssignmentPattern,
JsObjectBindingPattern, JsSyntaxKind, JsSyntaxToken,
};
use rome_rowan::{declare_node_union, AstNode, SyntaxNodeOptionExt, SyntaxResult};
declare_node_union! {
pub (crate) JsObjectPatternLike = JsObjectAssignmentPattern | JsObjectBindingPattern
}
impl JsObjectPatternLike {
fn l_curly_token(&self) -> SyntaxResult<JsSyntaxToken> {
match self {
JsObjectPatternLike::JsObjectAssignmentPattern(node) => node.l_curly_token(),
JsObjectPatternLike::JsObjectBindingPattern(node) => node.l_curly_token(),
}
}
fn r_curly_token(&self) -> SyntaxResult<JsSyntaxToken> {
match self {
JsObjectPatternLike::JsObjectAssignmentPattern(node) => node.r_curly_token(),
JsObjectPatternLike::JsObjectBindingPattern(node) => node.r_curly_token(),
}
}
fn is_empty(&self) -> bool {
match self {
JsObjectPatternLike::JsObjectAssignmentPattern(node) => node.properties().is_empty(),
JsObjectPatternLike::JsObjectBindingPattern(node) => node.properties().is_empty(),
}
}
fn write_properties(&self, f: &mut JsFormatter) -> FormatResult<()> {
match self {
JsObjectPatternLike::JsObjectAssignmentPattern(node) => {
write!(f, [node.properties().format()])
}
JsObjectPatternLike::JsObjectBindingPattern(node) => {
write!(f, [node.properties().format()])
}
}
}
fn is_inline(&self, comments: &JsComments) -> FormatResult<bool> {
let parent_kind = self.syntax().parent().kind();
Ok(
(matches!(parent_kind, Some(JsSyntaxKind::JS_FORMAL_PARAMETER))
|| self.is_hug_parameter(comments))
&& !self.l_curly_token()?.leading_trivia().has_skipped(),
)
}
fn should_break_properties(&self) -> bool {
let parent_kind = self.syntax().parent().kind();
let parent_where_not_to_break = matches!(
parent_kind,
Some(
// These parents are the kinds where we want to prevent
// to go to multiple lines.
JsSyntaxKind::JS_ARROW_FUNCTION_EXPRESSION
| JsSyntaxKind::JS_OBJECT_ASSIGNMENT_PATTERN_PROPERTY
| JsSyntaxKind::JS_CATCH_DECLARATION
| JsSyntaxKind::JS_OBJECT_BINDING_PATTERN_PROPERTY
)
);
if parent_where_not_to_break {
return false;
}
match self {
JsObjectPatternLike::JsObjectAssignmentPattern(node) => {
node.properties().iter().any(|property| {
if let Ok(
AnyJsObjectAssignmentPatternMember::JsObjectAssignmentPatternProperty(node),
) = property
{
let pattern = node.pattern();
matches!(
pattern,
Ok(AnyJsAssignmentPattern::JsObjectAssignmentPattern(_)
| AnyJsAssignmentPattern::JsArrayAssignmentPattern(_))
)
} else {
false
}
})
}
JsObjectPatternLike::JsObjectBindingPattern(node) => {
node.properties().iter().any(|property| {
if let Ok(AnyJsObjectBindingPatternMember::JsObjectBindingPatternProperty(
node,
)) = property
{
let pattern = node.pattern();
matches!(
pattern,
Ok(AnyJsBindingPattern::JsObjectBindingPattern(_)
| AnyJsBindingPattern::JsArrayBindingPattern(_))
)
} else {
false
}
})
}
}
}
fn is_in_assignment_like(&self) -> bool {
matches!(
self.syntax().parent().kind(),
Some(JsSyntaxKind::JS_ASSIGNMENT_EXPRESSION | JsSyntaxKind::JS_VARIABLE_DECLARATOR),
)
}
fn is_hug_parameter(&self, comments: &JsComments) -> bool {
match self {
JsObjectPatternLike::JsObjectAssignmentPattern(_) => false,
JsObjectPatternLike::JsObjectBindingPattern(binding) => binding
.parent::<AnyJsFormalParameter>()
.and_then(|parameter| parameter.syntax().grand_parent())
.and_then(FormatAnyJsParameters::cast)
.map_or(false, |parameters| {
should_hug_function_parameters(¶meters, comments).unwrap_or(false)
}),
}
}
fn layout(&self, comments: &JsComments) -> FormatResult<ObjectPatternLayout> {
if self.is_empty() {
return Ok(ObjectPatternLayout::Empty);
}
if self.is_inline(comments)? {
return Ok(ObjectPatternLayout::Inline);
}
let break_properties = self.should_break_properties();
let result = if break_properties {
ObjectPatternLayout::Group { expand: true }
} else if self.is_in_assignment_like() {
ObjectPatternLayout::Inline
} else {
ObjectPatternLayout::Group { expand: false }
};
Ok(result)
}
}
impl Format<JsFormatContext> for JsObjectPatternLike {
fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
let format_properties = format_with(|f| {
write!(
f,
[soft_space_or_block_indent(&format_with(
|f| self.write_properties(f)
))]
)
});
write!(f, [self.l_curly_token().format()])?;
match self.layout(f.comments())? {
ObjectPatternLayout::Empty => {
write!(
f,
[format_dangling_comments(self.syntax()).with_soft_block_indent()]
)?;
}
ObjectPatternLayout::Inline => {
write!(f, [format_properties])?;
}
ObjectPatternLayout::Group { expand } => {
write!(f, [group(&format_properties).should_expand(expand)])?;
}
}
write!(f, [self.r_curly_token().format()])
}
}
#[derive(Copy, Clone, Debug)]
enum ObjectPatternLayout {
/// Wrap the properties in a group with [`should_expand`](Group::should_expand) equal to `expand`.
///
/// This is the default layout when no other special case applies.
Group { expand: bool },
/// Layout for a pattern without any properties.
Empty,
/// Don't wrap the properties in a group and instead "inline" them in the parent.
///
/// Desired if the pattern is a parameter of a function that [should hug](should_hug_function_parameters) OR
/// if the pattern is the left side of an assignment.
Inline,
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/utils/format_modifiers.rs | crates/rome_js_formatter/src/utils/format_modifiers.rs | use crate::prelude::*;
use crate::utils::sort_modifiers_by_precedence;
use crate::{AsFormat, IntoFormat};
use rome_formatter::{format_args, write};
use rome_js_syntax::JsSyntaxKind::JS_DECORATOR;
use rome_js_syntax::{JsLanguage, Modifiers};
use rome_rowan::{AstNode, AstNodeList, NodeOrToken};
pub(crate) struct FormatModifiers<List> {
pub(crate) list: List,
}
impl<List> FormatModifiers<List> {
pub(crate) fn from(list: List) -> Self {
Self { list }
}
}
impl<List, Node> Format<JsFormatContext> for FormatModifiers<List>
where
Node: AstNode<Language = JsLanguage> + AsFormat<JsFormatContext> + IntoFormat<JsFormatContext>,
List: AstNodeList<Language = JsLanguage, Node = Node>,
Modifiers: for<'a> From<&'a Node>,
{
fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
let modifiers = sort_modifiers_by_precedence(&self.list);
let should_expand = should_expand_decorators(&self.list);
// need to use peek the iterator to check if the current node is a decorator and don't advance the iterator
let mut iter = modifiers.into_iter().peekable();
let decorators = format_once(|f| {
let mut join = f.join_nodes_with_soft_line();
// join only decorators here
while let Some(node) = iter.peek() {
// check if the current node is a decorator
match node.syntax().kind() {
JS_DECORATOR => {
join.entry(node.syntax(), &node.format());
// advance the iterator
iter.next();
}
_ => {
// if we encounter a non-decorator we break out of the loop
break;
}
}
}
join.finish()
});
write!(
f,
[group(&format_args![decorators, soft_line_break_or_space()])
.should_expand(should_expand)]
)?;
// join the rest of the modifiers
f.join_with(&space()).entries(iter.formatted()).finish()
}
}
/// This function expands decorators enclosing a group if there is a newline between decorators or after the last decorator.
pub(crate) fn should_expand_decorators<List, Node>(list: &List) -> bool
where
Node: AstNode<Language = JsLanguage>,
List: AstNodeList<Language = JsLanguage, Node = Node>,
{
// we need to skip the first node because we look for newlines between decorators or after the last decorator
for node in list.iter().skip(1) {
match node.syntax().kind() {
JS_DECORATOR => {
if node.syntax().has_leading_newline() {
return true;
}
}
_ => {
// if we encounter a non-decorator with a leading newline after a decorator and the next modifier
return node.syntax().has_leading_newline();
}
}
}
// if we encounter a non-decorator with a leading newline after a decorator and the next node or token
list.syntax_list()
.node()
.next_sibling_or_token()
.map_or(false, |node| match node {
NodeOrToken::Node(node) => node.has_leading_newline(),
NodeOrToken::Token(token) => token.has_leading_newline(),
})
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/utils/mod.rs | crates/rome_js_formatter/src/utils/mod.rs | pub(crate) mod array;
mod assignment_like;
mod binary_like_expression;
mod conditional;
pub mod string_utils;
pub(crate) mod format_class;
pub(crate) mod format_modifiers;
pub(crate) mod function_body;
pub mod jsx;
pub(crate) mod member_chain;
mod object;
mod object_like;
mod object_pattern_like;
#[cfg(test)]
mod quickcheck_utils;
pub(crate) mod test_call;
pub(crate) mod test_each_template;
mod typescript;
use crate::context::trailing_comma::FormatTrailingComma;
use crate::context::Semicolons;
use crate::parentheses::is_callee;
pub(crate) use crate::parentheses::resolve_left_most_expression;
use crate::prelude::*;
pub(crate) use assignment_like::{
with_assignment_layout, AnyJsAssignmentLike, AssignmentLikeLayout,
};
pub(crate) use binary_like_expression::{
needs_binary_like_parentheses, AnyJsBinaryLikeExpression, AnyJsBinaryLikeLeftExpression,
};
pub(crate) use conditional::{AnyJsConditional, ConditionalJsxChain};
pub(crate) use object_like::JsObjectLike;
pub(crate) use object_pattern_like::JsObjectPatternLike;
use rome_formatter::{format_args, write, Buffer};
use rome_js_syntax::JsSyntaxToken;
use rome_js_syntax::{
AnyJsExpression, AnyJsStatement, JsCallExpression, JsInitializerClause, JsLanguage, Modifiers,
};
use rome_rowan::{AstNode, AstNodeList};
pub(crate) use string_utils::*;
pub(crate) use typescript::{
is_object_like_type, should_hug_type, union_or_intersection_type_needs_parentheses,
TsIntersectionOrUnionTypeList,
};
/// Tests if expression is a long curried call
///
/// ```javascript
/// `connect(a, b, c)(d)`
/// ```
pub(crate) fn is_long_curried_call(expression: Option<&JsCallExpression>) -> bool {
if let Some(expression) = expression {
if let Some(parent_call) = expression.parent::<JsCallExpression>() {
if let (Ok(arguments), Ok(parent_arguments)) =
(expression.arguments(), parent_call.arguments())
{
return is_callee(expression.syntax(), parent_call.syntax())
&& arguments.args().len() > parent_arguments.args().len()
&& !parent_arguments.args().is_empty();
}
}
}
false
}
/// Utility function to format the separators of the nodes that belong to the unions
/// of [rome_js_syntax::TsAnyTypeMember].
///
/// We can have two kind of separators: `,`, `;` or ASI.
/// Because of how the grammar crafts the nodes, the parent will add the separator to the node.
/// So here, we create - on purpose - an empty node.
pub(crate) struct FormatTypeMemberSeparator<'a> {
token: Option<&'a JsSyntaxToken>,
}
impl<'a> FormatTypeMemberSeparator<'a> {
pub fn new(token: Option<&'a JsSyntaxToken>) -> Self {
Self { token }
}
}
impl Format<JsFormatContext> for FormatTypeMemberSeparator<'_> {
fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> {
if let Some(separator) = self.token {
format_removed(separator).fmt(f)
} else {
Ok(())
}
}
}
/// Utility function to format the node [rome_js_syntax::JsInitializerClause]
pub(crate) struct FormatInitializerClause<'a> {
initializer: Option<&'a JsInitializerClause>,
}
impl<'a> FormatInitializerClause<'a> {
pub fn new(initializer: Option<&'a JsInitializerClause>) -> Self {
Self { initializer }
}
}
impl Format<JsFormatContext> for FormatInitializerClause<'_> {
fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> {
if let Some(initializer) = self.initializer {
write!(f, [space(), initializer.format()])
} else {
Ok(())
}
}
}
pub(crate) struct FormatInterpreterToken<'a> {
token: Option<&'a JsSyntaxToken>,
}
impl<'a> FormatInterpreterToken<'a> {
pub fn new(interpreter_token: Option<&'a JsSyntaxToken>) -> Self {
Self {
token: interpreter_token,
}
}
}
impl Format<JsFormatContext> for FormatInterpreterToken<'_> {
fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> {
if let Some(interpreter) = self.token {
write!(f, [interpreter.format()])?;
match interpreter
.next_token()
.map_or(0, |next_token| get_lines_before_token(&next_token))
{
0 | 1 => write!(f, [hard_line_break()]),
_ => write!(f, [empty_line()]),
}
} else {
Ok(())
}
}
}
/// Formats the body of a statement where it can either be a single statement, an empty statement,
/// or a block statement.
pub(crate) struct FormatStatementBody<'a> {
body: &'a AnyJsStatement,
force_space: bool,
}
impl<'a> FormatStatementBody<'a> {
pub fn new(body: &'a AnyJsStatement) -> Self {
Self {
body,
force_space: false,
}
}
/// Prevents that the consequent is formatted on its own line and indented by one level and
/// instead gets separated by a space.
pub fn with_forced_space(mut self, forced: bool) -> Self {
self.force_space = forced;
self
}
}
impl Format<JsFormatContext> for FormatStatementBody<'_> {
fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
use AnyJsStatement::*;
if let JsEmptyStatement(empty) = &self.body {
write!(f, [empty.format()])
} else if matches!(&self.body, JsBlockStatement(_)) || self.force_space {
write!(f, [space(), self.body.format()])
} else {
write!(
f,
[indent(&format_args![
soft_line_break_or_space(),
self.body.format()
])]
)
}
}
}
/// This function consumes a list of modifiers and applies a predictable sorting.
pub(crate) fn sort_modifiers_by_precedence<List, Node>(list: &List) -> Vec<Node>
where
Node: AstNode<Language = JsLanguage>,
List: AstNodeList<Language = JsLanguage, Node = Node>,
Modifiers: for<'a> From<&'a Node>,
{
let mut nodes_and_modifiers = list.iter().collect::<Vec<Node>>();
nodes_and_modifiers.sort_unstable_by_key(|node| Modifiers::from(node));
nodes_and_modifiers
}
pub(crate) type FormatStatementSemicolon<'a> = FormatOptionalSemicolon<'a>;
/// Formats a semicolon in a position where it is optional (not needed to maintain syntactical correctness).
///
/// * Inserts a new semicolon if it is absent and [JsFormatOptions::semicolons] is [Semicolons::Always].
/// * Removes the semicolon if it is present and [JsFormatOptions::semicolons] is [Semicolons::AsNeeded].
pub(crate) struct FormatOptionalSemicolon<'a> {
semicolon: Option<&'a JsSyntaxToken>,
}
impl<'a> FormatOptionalSemicolon<'a> {
pub(crate) fn new(semicolon: Option<&'a JsSyntaxToken>) -> Self {
Self { semicolon }
}
}
impl Format<JsFormatContext> for FormatOptionalSemicolon<'_> {
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 {
None => Ok(()),
Some(semicolon) => format_removed(semicolon).fmt(f),
},
}
}
}
/// Format some code followed by an optional semicolon.
/// Performs semicolon insertion if it is missing in the input source, the [semicolons option](crate::JsFormatOptions::semicolons) is [Semicolons::Always], and the
/// preceding element isn't an bogus node
pub(crate) struct FormatSemicolon<'a> {
semicolon: Option<&'a JsSyntaxToken>,
}
impl<'a> FormatSemicolon<'a> {
pub fn new(semicolon: Option<&'a JsSyntaxToken>) -> Self {
Self { semicolon }
}
}
impl Format<JsFormatContext> for FormatSemicolon<'_> {
fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> {
match self.semicolon {
Some(semicolon) => semicolon.format().fmt(f),
None => {
let is_after_bogus = f.elements().start_tag(TagKind::Verbatim).map_or(
false,
|signal| match signal {
Tag::StartVerbatim(kind) => kind.is_bogus(),
_ => unreachable!(),
},
);
if !is_after_bogus {
write!(f, [text(";")])?;
}
Ok(())
}
}
}
}
/// A call like expression is one of:
///
/// - [JsNewExpression]
/// - [JsImportCallExpression]
/// - [JsCallExpression]
pub(crate) fn is_call_like_expression(expression: &AnyJsExpression) -> bool {
matches!(
expression,
AnyJsExpression::JsNewExpression(_)
| AnyJsExpression::JsImportCallExpression(_)
| AnyJsExpression::JsCallExpression(_)
)
}
/// This function is in charge to format the call arguments.
pub(crate) fn write_arguments_multi_line<S: Format<JsFormatContext>, I>(
separated: I,
f: &mut JsFormatter,
) -> FormatResult<()>
where
I: Iterator<Item = S>,
{
let mut iterator = separated.peekable();
let mut join_with = f.join_with(soft_line_break_or_space());
while let Some(element) = iterator.next() {
let last = iterator.peek().is_none();
if last {
join_with.entry(&format_args![&element, FormatTrailingComma::All]);
} else {
join_with.entry(&element);
}
}
join_with.finish()
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/utils/test_call.rs | crates/rome_js_formatter/src/utils/test_call.rs | use crate::prelude::*;
use rome_js_syntax::{
AnyJsArrowFunctionParameters, AnyJsCallArgument, AnyJsExpression, AnyJsFunctionBody,
AnyJsLiteralExpression, AnyJsName, AnyJsTemplateElement, JsCallArgumentList, JsCallArguments,
JsCallExpression, JsSyntaxNode, JsTemplateExpression,
};
use rome_rowan::{SyntaxResult, TokenText};
/// Returns `Ok(true)` if `maybe_argument` is an argument of a [test call expression](is_test_call_expression).
pub(crate) fn is_test_call_argument(maybe_argument: &JsSyntaxNode) -> SyntaxResult<bool> {
let call_expression = maybe_argument
.parent()
.and_then(JsCallArgumentList::cast)
.and_then(|args| args.syntax().grand_parent())
.and_then(JsCallExpression::cast);
call_expression.map_or(Ok(false), |call| is_test_call_expression(&call))
}
/// This is a specialised function that checks if the current [call expression]
/// resembles a call expression usually used by a testing frameworks.
///
/// If the [call expression] matches the criteria, a different formatting is applied.
///
/// To evaluable the eligibility of a [call expression] to be a test framework like,
/// we need to check its [callee] and its [arguments].
///
/// 1. The [callee] must contain a name or a chain of names that belongs to the
/// test frameworks, for example: `test()`, `test.only()`, etc.
/// 2. The [arguments] should be at the least 2
/// 3. The first argument has to be a string literal
/// 4. The third argument, if present, has to be a number literal
/// 5. The second argument has to be an [arrow function expression] or [function expression]
/// 6. Both function must have zero or one parameters
///
/// [call expression]: crate::rome_js_syntax::JsCallExpression
/// [callee]: crate::rome_js_syntax::AnyJsExpression
/// [arguments]: crate::rome_js_syntax::JsCallArgumentList
/// [arrow function expression]: crate::rome_js_syntax::JsArrowFunctionExpression
/// [function expression]: crate::rome_js_syntax::JsCallArgumentList
pub(crate) fn is_test_call_expression(call_expression: &JsCallExpression) -> SyntaxResult<bool> {
use AnyJsExpression::*;
let callee = call_expression.callee()?;
let arguments = call_expression.arguments()?;
let mut args = arguments.args().iter();
match (args.next(), args.next(), args.next()) {
(Some(Ok(argument)), None, None) if arguments.args().len() == 1 => {
if is_angular_test_wrapper(&call_expression.clone().into())
&& call_expression
.parent::<JsCallArgumentList>()
.and_then(|arguments_list| arguments_list.parent::<JsCallArguments>())
.and_then(|arguments| arguments.parent::<self::JsCallExpression>())
.map_or(Ok(false), |parent| is_test_call_expression(&parent))?
{
return Ok(matches!(
argument,
AnyJsCallArgument::AnyJsExpression(
JsArrowFunctionExpression(_) | JsFunctionExpression(_)
)
));
}
if is_unit_test_set_up_callee(&callee) {
return Ok(argument
.as_any_js_expression()
.map_or(false, is_angular_test_wrapper));
}
Ok(false)
}
// it("description", ..)
(
Some(Ok(AnyJsCallArgument::AnyJsExpression(
JsTemplateExpression(_)
| AnyJsLiteralExpression(self::AnyJsLiteralExpression::JsStringLiteralExpression(_)),
))),
Some(Ok(second)),
third,
) if arguments.args().len() <= 3 && contains_a_test_pattern(&callee)? => {
// it('name', callback, duration)
if !matches!(
third,
None | Some(Ok(AnyJsCallArgument::AnyJsExpression(
AnyJsLiteralExpression(
self::AnyJsLiteralExpression::JsNumberLiteralExpression(_)
)
)))
) {
return Ok(false);
}
if second
.as_any_js_expression()
.map_or(false, is_angular_test_wrapper)
{
return Ok(true);
}
let (parameters, has_block_body) = match second {
AnyJsCallArgument::AnyJsExpression(JsFunctionExpression(function)) => (
function
.parameters()
.map(AnyJsArrowFunctionParameters::from),
true,
),
AnyJsCallArgument::AnyJsExpression(JsArrowFunctionExpression(arrow)) => (
arrow.parameters(),
arrow.body().map_or(false, |body| {
matches!(body, AnyJsFunctionBody::JsFunctionBody(_))
}),
),
_ => return Ok(false),
};
Ok(arguments.args().len() == 2 || (parameters?.len() <= 1 && has_block_body))
}
_ => Ok(false),
}
}
/// Note: `inject` is used in AngularJS 1.x, `async` and `fakeAsync` in
/// Angular 2+, although `async` is deprecated and replaced by `waitForAsync`
/// since Angular 12.
///
/// example: https://docs.angularjs.org/guide/unit-testing#using-beforeall-
///
/// @param {CallExpression} node
/// @returns {boolean}
///
fn is_angular_test_wrapper(expression: &AnyJsExpression) -> bool {
use AnyJsExpression::*;
match expression {
JsCallExpression(call_expression) => match call_expression.callee() {
Ok(JsIdentifierExpression(identifier)) => identifier
.name()
.and_then(|name| name.value_token())
.map_or(false, |name| {
matches!(
name.text_trimmed(),
"async" | "inject" | "fakeAsync" | "waitForAsync"
)
}),
_ => false,
},
_ => false,
}
}
/// Tests if the callee is a `beforeEach`, `beforeAll`, `afterEach` or `afterAll` identifier
/// that is commonly used in test frameworks.
fn is_unit_test_set_up_callee(callee: &AnyJsExpression) -> bool {
match callee {
AnyJsExpression::JsIdentifierExpression(identifier) => identifier
.name()
.and_then(|name| name.value_token())
.map_or(false, |name| {
matches!(
name.text_trimmed(),
"beforeEach" | "beforeAll" | "afterEach" | "afterAll"
)
}),
_ => false,
}
}
pub(crate) fn is_test_each_pattern(template: &JsTemplateExpression) -> bool {
is_test_each_pattern_callee(template) && is_test_each_pattern_elements(template)
}
fn is_test_each_pattern_elements(template: &JsTemplateExpression) -> bool {
let mut iter = template.elements().into_iter();
// the table must have a header as JsTemplateChunkElement
// e.g. a | b | expected
if !matches!(
iter.next(),
Some(AnyJsTemplateElement::JsTemplateChunkElement(_))
) {
return false;
}
// Guarding against skipped token trivia on elements that we remove.
// Because that would result in the skipped token trivia being emitted before the template.
for element in template.elements() {
if let AnyJsTemplateElement::JsTemplateChunkElement(element) = element {
if let Some(leading_trivia) = element.syntax().first_leading_trivia() {
if leading_trivia.has_skipped() {
return false;
}
}
}
}
true
}
/// This function checks if a call expressions has one of the following members:
/// - `describe.each`
/// - `describe.only.each`
/// - `describe.skip.each`
/// - `test.concurrent.each`
/// - `test.concurrent.only.each`
/// - `test.concurrent.skip.each`
/// - `test.each`
/// - `test.only.each`
/// - `test.skip.each`
/// - `test.failing.each`
/// - `it.concurrent.each`
/// - `it.concurrent.only.each`
/// - `it.concurrent.skip.each`
/// - `it.each`
/// - `it.only.each`
/// - `it.skip.each`
/// - `it.failing.each`
///
/// - `xdescribe.each`
/// - `xdescribe.only.each`
/// - `xdescribe.skip.each`
/// - `xtest.concurrent.each`
/// - `xtest.concurrent.only.each`
/// - `xtest.concurrent.skip.each`
/// - `xtest.each`
/// - `xtest.only.each`
/// - `xtest.skip.each`
/// - `xtest.failing.each`
/// - `xit.concurrent.each`
/// - `xit.concurrent.only.each`
/// - `xit.concurrent.skip.each`
/// - `xit.each`
/// - `xit.only.each`
/// - `xit.skip.each`
/// - `xit.failing.each`
///
/// - `fdescribe.each`
/// - `fdescribe.only.each`
/// - `fdescribe.skip.each`
/// - `ftest.concurrent.each`
/// - `ftest.concurrent.only.each`
/// - `ftest.concurrent.skip.each`
/// - `ftest.each`
/// - `ftest.only.each`
/// - `ftest.skip.each`
/// - `ftest.failing.each`
/// - `fit.concurrent.each`
/// - `fit.concurrent.only.each`
/// - `fit.concurrent.skip.each`
/// - `fit.each`
/// - `fit.only.each`
/// - `fit.skip.each`
/// - `xit.failing.each`
///
/// Based on this [article]
///
/// [article]: https://craftinginterpreters.com/scanning-on-demand.html#tries-and-state-machines
fn is_test_each_pattern_callee(template: &JsTemplateExpression) -> bool {
if let Some(tag) = template.tag() {
let mut members = CalleeNamesIterator::new(tag);
let texts: [Option<TokenText>; 5] = [
members.next(),
members.next(),
members.next(),
members.next(),
members.next(),
];
let mut rev = texts.iter().rev().flatten();
let first = rev.next().map(|t| t.text());
let second = rev.next().map(|t| t.text());
let third = rev.next().map(|t| t.text());
let fourth = rev.next().map(|t| t.text());
let fifth = rev.next().map(|t| t.text());
match first {
Some("describe" | "xdescribe" | "fdescribe") => match second {
Some("each") => third.is_none(),
Some("skip" | "only") => match third {
Some("each") => fourth.is_none(),
_ => false,
},
_ => false,
},
Some("test" | "xtest" | "ftest" | "it" | "xit" | "fit") => match second {
Some("each") => third.is_none(),
Some("skip" | "only" | "failing") => match third {
Some("each") => fourth.is_none(),
_ => false,
},
Some("concurrent") => match third {
Some("each") => fourth.is_none(),
Some("only" | "skip") => match fourth {
Some("each") => fifth.is_none(),
_ => false,
},
_ => false,
},
_ => false,
},
_ => false,
}
} else {
false
}
}
/// This function checks if a call expressions has one of the following members:
/// - `it`
/// - `it.only`
/// - `it.skip`
/// - `describe`
/// - `describe.only`
/// - `describe.skip`
/// - `test`
/// - `test.only`
/// - `test.skip`
/// - `test.step`
/// - `test.describe`
/// - `test.describe.only`
/// - `test.describe.parallel`
/// - `test.describe.parallel.only`
/// - `test.describe.serial`
/// - `test.describe.serial.only`
/// - `skip`
/// - `xit`
/// - `xdescribe`
/// - `xtest`
/// - `fit`
/// - `fdescribe`
/// - `ftest`
///
/// Based on this [article]
///
/// [article]: https://craftinginterpreters.com/scanning-on-demand.html#tries-and-state-machines
fn contains_a_test_pattern(callee: &AnyJsExpression) -> SyntaxResult<bool> {
let mut members = CalleeNamesIterator::new(callee.clone());
let texts: [Option<TokenText>; 5] = [
members.next(),
members.next(),
members.next(),
members.next(),
members.next(),
];
let mut rev = texts.iter().rev().flatten();
let first = rev.next().map(|t| t.text());
let second = rev.next().map(|t| t.text());
let third = rev.next().map(|t| t.text());
let fourth = rev.next().map(|t| t.text());
let fifth = rev.next().map(|t| t.text());
Ok(match first {
Some("it" | "describe") => match second {
None => true,
Some("only" | "skip") => third.is_none(),
_ => false,
},
Some("test") => match second {
None => true,
Some("only" | "skip" | "step") => third.is_none(),
Some("describe") => match third {
None => true,
Some("only") => true,
Some("parallel" | "serial") => match fourth {
None => true,
Some("only") => fifth.is_none(),
_ => false,
},
_ => false,
},
_ => false,
},
Some("skip" | "xit" | "xdescribe" | "xtest" | "fit" | "fdescribe" | "ftest") => true,
_ => false,
})
}
/// Iterator that returns the callee names in "top down order".
///
/// # Examples
///
/// ```javascript
/// it.only() -> [`only`, `it`]
/// ```
struct CalleeNamesIterator {
next: Option<AnyJsExpression>,
}
impl CalleeNamesIterator {
fn new(callee: AnyJsExpression) -> Self {
Self { next: Some(callee) }
}
}
impl Iterator for CalleeNamesIterator {
type Item = TokenText;
fn next(&mut self) -> Option<Self::Item> {
use AnyJsExpression::*;
let current = self.next.take()?;
match current {
JsIdentifierExpression(identifier) => identifier
.name()
.and_then(|reference| reference.value_token())
.ok()
.map(|value| value.token_text_trimmed()),
JsStaticMemberExpression(member_expression) => match member_expression.member() {
Ok(AnyJsName::JsName(name)) => {
self.next = member_expression.object().ok();
name.value_token()
.ok()
.map(|name| name.token_text_trimmed())
}
_ => None,
},
_ => None,
}
}
}
#[cfg(test)]
mod test {
use super::{contains_a_test_pattern, is_test_each_pattern_callee};
use rome_js_parser::{parse, JsParserOptions};
use rome_js_syntax::{JsCallExpression, JsFileSource, JsTemplateExpression};
use rome_rowan::AstNodeList;
fn extract_call_expression(src: &str) -> JsCallExpression {
let source_type = JsFileSource::js_module();
let result = parse(src, source_type, JsParserOptions::default());
let module = result
.tree()
.as_js_module()
.unwrap()
.items()
.first()
.unwrap();
module
.as_any_js_statement()
.unwrap()
.as_js_expression_statement()
.unwrap()
.expression()
.unwrap()
.as_js_call_expression()
.unwrap()
.clone()
}
fn extract_template(src: &str) -> JsTemplateExpression {
let source_type = JsFileSource::js_module();
let result = parse(src, source_type, JsParserOptions::default());
let module = result
.tree()
.as_js_module()
.unwrap()
.items()
.first()
.unwrap();
module
.as_any_js_statement()
.unwrap()
.as_js_expression_statement()
.unwrap()
.expression()
.unwrap()
.as_js_template_expression()
.unwrap()
.clone()
}
#[test]
fn matches_simple_call() {
let call_expression = extract_call_expression("test();");
assert_eq!(
contains_a_test_pattern(&call_expression.callee().unwrap()),
Ok(true)
);
let call_expression = extract_call_expression("it();");
assert_eq!(
contains_a_test_pattern(&call_expression.callee().unwrap()),
Ok(true)
);
}
#[test]
fn matches_static_member_expression() {
let call_expression = extract_call_expression("test.only();");
assert_eq!(
contains_a_test_pattern(&call_expression.callee().unwrap()),
Ok(true)
);
}
#[test]
fn matches_static_member_expression_deep() {
let call_expression = extract_call_expression("test.describe.parallel.only();");
assert_eq!(
contains_a_test_pattern(&call_expression.callee().unwrap()),
Ok(true)
);
}
#[test]
fn doesnt_static_member_expression_deep() {
let call_expression = extract_call_expression("test.describe.parallel.only.AHAHA();");
assert_eq!(
contains_a_test_pattern(&call_expression.callee().unwrap()),
Ok(false)
);
}
#[test]
fn matches_simple_each() {
let template = extract_template("describe.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("test.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("it.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("xdescribe.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("xtest.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("xit.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("fdescribe.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("ftest.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("fit.each``");
assert!(is_test_each_pattern_callee(&template));
}
#[test]
fn matches_skip_each() {
let template = extract_template("describe.skip.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("test.skip.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("it.skip.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("xdescribe.skip.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("xtest.skip.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("xit.skip.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("fdescribe.skip.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("ftest.skip.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("fit.skip.each``");
assert!(is_test_each_pattern_callee(&template));
}
#[test]
fn matches_only_each() {
let template = extract_template("describe.only.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("test.only.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("it.only.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("xdescribe.only.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("xtest.only.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("xit.only.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("fdescribe.only.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("ftest.only.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("fit.only.each``");
assert!(is_test_each_pattern_callee(&template));
}
#[test]
fn matches_failing_each() {
let template = extract_template("test.failing.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("it.failing.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("xtest.failing.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("xit.failing.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("ftest.failing.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("fit.failing.each``");
assert!(is_test_each_pattern_callee(&template));
}
#[test]
fn matches_concurrent_each() {
let template = extract_template("test.concurrent.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("it.concurrent.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("xtest.concurrent.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("xit.concurrent.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("ftest.concurrent.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("fit.concurrent.each``");
assert!(is_test_each_pattern_callee(&template));
}
#[test]
fn matches_concurrent_only_each() {
let template = extract_template("test.concurrent.only.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("it.concurrent.only.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("xtest.concurrent.only.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("xit.concurrent.only.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("ftest.concurrent.only.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("fit.concurrent.only.each``");
assert!(is_test_each_pattern_callee(&template));
}
#[test]
fn matches_concurrent_skip_each() {
let template = extract_template("test.concurrent.skip.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("it.concurrent.skip.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("xtest.concurrent.skip.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("xit.concurrent.skip.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("ftest.concurrent.skip.each``");
assert!(is_test_each_pattern_callee(&template));
let template = extract_template("fit.concurrent.skip.each``");
assert!(is_test_each_pattern_callee(&template));
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/utils/format_class.rs | crates/rome_js_formatter/src/utils/format_class.rs | use crate::prelude::*;
use rome_formatter::{format_args, write};
use rome_js_syntax::AnyJsClass;
pub struct FormatClass<'a> {
class: &'a AnyJsClass,
}
impl FormatClass<'_> {
fn should_group(&self, comments: &JsComments) -> FormatResult<bool> {
if let Some(id) = self.class.id()? {
if comments.has_trailing_comments(id.syntax()) {
return Ok(true);
}
}
if let Some(type_parameters) = self.class.type_parameters() {
if comments.has_trailing_comments(type_parameters.syntax()) {
return Ok(true);
}
}
if let Some(extends) = self.class.extends_clause() {
if comments.has_trailing_comments(extends.syntax()) {
return Ok(true);
}
}
if self.class.implements_clause().is_some() {
return Ok(true);
}
Ok(false)
}
}
impl<'a> From<&'a AnyJsClass> for FormatClass<'a> {
fn from(class: &'a AnyJsClass) -> Self {
Self { class }
}
}
impl Format<JsFormatContext> for FormatClass<'_> {
fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
let decorators = self.class.decorators();
let abstract_token = self.class.abstract_token();
let id = self.class.id()?;
let extends = self.class.extends_clause();
let implements_clause = self.class.implements_clause();
let type_parameters = self.class.type_parameters();
let class_token = self.class.class_token()?;
let members = self.class.members();
let group_mode = self.should_group(f.comments())?;
write!(f, [decorators.format()])?;
if let Some(abstract_token) = abstract_token {
write!(f, [abstract_token.format(), space()])?;
}
write!(f, [class_token.format()])?;
let indent_only_heritage = type_parameters.as_ref().map_or(false, |type_parameters| {
!f.comments()
.has_trailing_line_comment(type_parameters.syntax())
}) && !(extends.is_some() && implements_clause.is_some());
let type_parameters_id = if indent_only_heritage && implements_clause.is_some() {
Some(f.group_id("type_parameters"))
} else {
None
};
let head = format_with(|f| {
if let Some(id) = &id {
write!(f, [space(), id.format()])?;
}
if let Some(type_parameters) = &type_parameters {
write!(
f,
[type_parameters.format().with_options(type_parameters_id)]
)?;
}
Ok(())
});
let format_heritage_clauses = format_with(|f| {
if let Some(extends) = &extends {
if group_mode {
write!(f, [soft_line_break_or_space(), group(&extends.format())])?;
} else {
write!(f, [space(), extends.format()])?;
}
}
if let Some(implements_clause) = &implements_clause {
if indent_only_heritage {
write!(
f,
[
if_group_breaks(&space()).with_group_id(type_parameters_id),
if_group_fits_on_line(&soft_line_break_or_space())
.with_group_id(type_parameters_id)
]
)?;
} else {
write!(f, [soft_line_break_or_space()])?;
}
write!(f, [implements_clause.format()])?;
}
Ok(())
});
if group_mode {
let indented = format_with(|f| {
if indent_only_heritage {
write!(f, [head, indent(&format_heritage_clauses)])
} else {
write!(f, [indent(&format_args![head, format_heritage_clauses])])
}
});
let heritage_id = f.group_id("heritageGroup");
write!(
f,
[group(&indented).with_group_id(Some(heritage_id)), space()]
)?;
if !members.is_empty() {
write!(
f,
[if_group_breaks(&hard_line_break()).with_group_id(Some(heritage_id))]
)?;
}
} else {
write!(f, [head, format_heritage_clauses, space()])?;
}
if members.is_empty() {
write!(
f,
[
self.class.l_curly_token().format(),
format_dangling_comments(self.class.syntax()).with_block_indent(),
self.class.r_curly_token().format()
]
)
} else {
write![
f,
[
self.class.l_curly_token().format(),
block_indent(&members.format()),
self.class.r_curly_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/utils/conditional.rs | crates/rome_js_formatter/src/utils/conditional.rs | use crate::prelude::*;
use rome_formatter::{
write, CstFormatContext, FormatContext, FormatOwnedWithRule, FormatRefWithRule,
FormatRuleWithOptions,
};
use crate::{AsFormat, IntoFormat};
use rome_js_syntax::{
AnyJsExpression, AnyTsType, JsAssignmentExpression, JsCallExpression,
JsComputedMemberExpression, JsConditionalExpression, JsFileSource, JsInitializerClause,
JsNewExpression, JsReturnStatement, JsStaticMemberExpression, JsSyntaxKind, JsSyntaxNode,
JsSyntaxToken, JsThrowStatement, JsUnaryExpression, JsYieldArgument, TsAsExpression,
TsConditionalType, TsNonNullAssertionExpression, TsSatisfiesExpression,
};
use rome_rowan::{declare_node_union, match_ast, AstNode, SyntaxResult};
declare_node_union! {
pub AnyJsConditional = JsConditionalExpression | TsConditionalType
}
impl AsFormat<JsFormatContext> for AnyJsConditional {
type Format<'a> = FormatRefWithRule<'a, AnyJsConditional, FormatJsAnyConditionalRule>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(self, FormatJsAnyConditionalRule::default())
}
}
impl IntoFormat<JsFormatContext> for AnyJsConditional {
type Format = FormatOwnedWithRule<AnyJsConditional, FormatJsAnyConditionalRule>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(self, FormatJsAnyConditionalRule::default())
}
}
#[derive(Debug, Copy, Clone, Default)]
pub struct FormatJsAnyConditionalRule {
/// Whether the parent is a jsx conditional chain.
/// Gets passed through from the root to the consequent and alternate of [JsConditionalExpression]s.
///
/// Doesn't apply for [TsConditionalType].
jsx_chain: ConditionalJsxChain,
}
impl FormatRuleWithOptions<AnyJsConditional> for FormatJsAnyConditionalRule {
type Options = ConditionalJsxChain;
fn with_options(mut self, options: Self::Options) -> Self {
self.jsx_chain = options;
self
}
}
impl FormatRule<AnyJsConditional> for FormatJsAnyConditionalRule {
type Context = JsFormatContext;
fn fmt(
&self,
conditional: &AnyJsConditional,
f: &mut Formatter<Self::Context>,
) -> FormatResult<()> {
let syntax = conditional.syntax();
let consequent = conditional.consequent()?;
let alternate = conditional.alternate()?;
let layout = self.layout(conditional, f.context().options().source_type());
let jsx_chain = layout.jsx_chain().unwrap_or(self.jsx_chain);
let format_consequent_and_alternate = format_with(|f| {
write!(
f,
[
soft_line_break_or_space(),
conditional.question_mark_token().format(),
space()
]
)?;
let is_consequent_nested = consequent.syntax().kind() == syntax.kind();
if is_consequent_nested {
// Add parentheses around the consequent if it is a conditional expression and fits on the same line
// so that it's easier to identify the parts that belong to a conditional expression.
// `a ? b ? c: d : e` -> `a ? (b ? c: d) : e
write!(
f,
[
if_group_fits_on_line(&text("(")),
align(2, &consequent),
if_group_fits_on_line(&text(")"))
]
)?;
} else {
write!(f, [align(2, &consequent)])?;
}
write!(
f,
[
soft_line_break_or_space(),
conditional.colon_token().format(),
space()
]
)?;
let is_alternate_nested = alternate.syntax().kind() == syntax.kind();
// Don't "indent" a nested alternate by two spaces so that the consequent and alternates nicely align
// ```
// // Prefer **this** over // **this**
// aLongLongLongLong aLongLongLongLong
// ? bLongLongLongLong ? bLongLongLongLong
// : cLongLongLong : cLongLongLong
// ? dLongLongLong ? dLongLong
// : eLongLongLong; : eLongLongLong
// ```
if is_alternate_nested {
write!(f, [alternate])
} else {
write!(f, [align(2, &alternate)])
}
});
let format_tail_with_indent = format_with(|f: &mut JsFormatter| {
match conditional {
AnyJsConditional::JsConditionalExpression(conditional) if jsx_chain.is_chain() => {
write!(
f,
[
space(),
conditional.question_mark_token().format(),
space(),
format_jsx_chain_consequent(consequent.as_expression().unwrap()),
space(),
conditional.colon_token().format(),
space(),
format_jsx_chain_alternate(alternate.as_expression().unwrap())
]
)
}
_ => {
// Add an extra level of indent to nested consequences.
if layout.is_nested_consequent() {
// This may look silly but the `dedent` is to remove the outer `align` added by the parent's formatting of the consequent.
// The `indent` is necessary to indent the content by one level with a tab.
// Adding an `indent` without the `dedent` would result in the `outer` align being converted
// into a `indent` + the `indent` added here, ultimately resulting in a two-level indention.
write!(f, [dedent(&indent(&format_consequent_and_alternate))])
} else {
format_consequent_and_alternate.fmt(f)
}
}
}
});
let should_extra_indent = self.should_extra_indent(conditional, &layout);
let format_inner = format_with(|f| {
write!(
f,
[FormatConditionalTest {
conditional,
layout: &layout,
}]
)?;
// Indent the `consequent` and `alternate` **only if** this is the root conditional expression
// OR this is the `test` of a conditional expression.
if jsx_chain.is_no_chain() && (layout.is_root() || layout.is_nested_test()) {
write!(f, [indent(&format_tail_with_indent)])?;
} else {
// Don't indent for nested `alternate`s or `consequence`s
write!(f, [format_tail_with_indent])?;
}
let break_closing_parentheses = jsx_chain.is_no_chain()
&& self.is_parent_static_member_expression(conditional, &layout);
// Add a soft line break in front of the closing `)` in case the parent is a static member expression
// ```
// (veryLongCondition
// ? a
// : b // <- enforce line break here if the conditional breaks
// ).more
// ```
if break_closing_parentheses && !should_extra_indent {
write!(f, [soft_line_break()])?;
}
Ok(())
});
let grouped = format_with(|f| {
if layout.is_root() {
group(&format_inner).fmt(f)
} else {
format_inner.fmt(f)
}
});
let has_multiline_comment = {
let comments = f.context().comments();
let has_block_comment = |syntax: &JsSyntaxNode| {
comments
.leading_trailing_comments(syntax)
.any(|comment| comment.kind().is_block())
};
let test_has_block_comments = match conditional {
AnyJsConditional::JsConditionalExpression(expression) => {
has_block_comment(expression.test()?.syntax())
}
AnyJsConditional::TsConditionalType(ty) => {
has_block_comment(ty.check_type()?.syntax())
|| has_block_comment(ty.extends_type()?.syntax())
}
};
test_has_block_comments
|| has_block_comment(consequent.syntax())
|| has_block_comment(alternate.syntax())
};
if layout.is_nested_test() || should_extra_indent {
group(&soft_block_indent(&grouped))
.should_expand(has_multiline_comment)
.fmt(f)
} else {
if has_multiline_comment {
write!(f, [expand_parent()])?;
}
grouped.fmt(f)
}
}
}
impl FormatJsAnyConditionalRule {
fn layout(
&self,
conditional: &AnyJsConditional,
source_type: JsFileSource,
) -> ConditionalLayout {
match conditional.syntax().parent() {
Some(parent) if parent.kind() == conditional.syntax().kind() => {
let conditional_parent = AnyJsConditional::unwrap_cast(parent);
if conditional_parent.is_test(conditional.syntax()) {
ConditionalLayout::NestedTest {
parent: conditional_parent,
}
} else if conditional_parent.is_alternate(conditional.syntax()) {
ConditionalLayout::NestedAlternate {
parent: conditional_parent,
}
} else {
ConditionalLayout::NestedConsequent {
parent: conditional_parent,
}
}
}
parent => {
let is_jsx_chain = match conditional {
AnyJsConditional::JsConditionalExpression(conditional)
if source_type.variant().is_jsx() =>
{
is_jsx_conditional_chain(conditional)
}
_ => false,
};
ConditionalLayout::Root {
parent,
jsx_chain: is_jsx_chain.into(),
}
}
}
}
/// It is desired to add an extra indent if this conditional is a [JsConditionalExpression] and is directly inside
/// of a member chain:
///
/// ```javascript
/// // Input
/// return (a ? b : c).member
///
/// // Default
/// return (a
/// ? b
/// : c
/// ).member
///
/// // Preferred
/// return (
/// a
/// ? b
/// : c
/// ).member
/// ```
fn should_extra_indent(
&self,
conditional: &AnyJsConditional,
layout: &ConditionalLayout,
) -> bool {
enum Ancestor {
MemberChain(AnyJsExpression),
Root(JsSyntaxNode),
}
let conditional = match conditional {
AnyJsConditional::JsConditionalExpression(conditional) => conditional,
AnyJsConditional::TsConditionalType(_) => {
return false;
}
};
let ancestors = layout
.parent()
.into_iter()
.flat_map(|parent| parent.ancestors());
let mut parent = None;
let mut expression = AnyJsExpression::from(conditional.clone());
// This tries to find the start of a member chain by iterating over all ancestors of the conditional.
// The iteration "breaks" as soon as a non-member-chain node is found.
for ancestor in ancestors {
let ancestor = match_ast! {
match &ancestor {
JsCallExpression(call_expression) => {
if call_expression
.callee()
.as_ref()
== Ok(&expression)
{
Ancestor::MemberChain(call_expression.into())
} else {
Ancestor::Root(call_expression.into_syntax())
}
},
JsStaticMemberExpression(member_expression) => {
if member_expression
.object()
.as_ref()
== Ok(&expression)
{
Ancestor::MemberChain(member_expression.into())
} else {
Ancestor::Root(member_expression.into_syntax())
}
},
JsComputedMemberExpression(member_expression) => {
if member_expression
.object()
.as_ref()
== Ok(&expression)
{
Ancestor::MemberChain(member_expression.into())
} else {
Ancestor::Root(member_expression.into_syntax())
}
},
TsNonNullAssertionExpression(non_null_assertion) => {
if non_null_assertion
.expression()
.as_ref()
== Ok(&expression)
{
Ancestor::MemberChain(non_null_assertion.into())
} else {
Ancestor::Root(non_null_assertion.into_syntax())
}
},
JsNewExpression(new_expression) => {
// Skip over new expressions
if new_expression
.callee()
.as_ref()
== Ok(&expression)
{
parent = new_expression.syntax().parent();
expression = new_expression.into();
break;
}
Ancestor::Root(new_expression.into_syntax())
},
TsAsExpression(as_expression) => {
if as_expression
.expression()
.as_ref()
== Ok(&expression)
{
parent = as_expression.syntax().parent();
expression = as_expression.into();
break;
}
Ancestor::Root(as_expression.into_syntax())
},
TsSatisfiesExpression(satisfies_expression) => {
if satisfies_expression
.expression()
.as_ref()
== Ok(&expression)
{
parent = satisfies_expression.syntax().parent();
expression = satisfies_expression.into();
break;
}
Ancestor::Root(satisfies_expression.into_syntax())
},
_ => Ancestor::Root(ancestor),
}
};
match ancestor {
Ancestor::MemberChain(left) => {
// Store the node that is highest in the member chain
expression = left;
}
Ancestor::Root(root) => {
parent = Some(root);
break;
}
}
}
// Don't indent if this conditional isn't part of a member chain.
// e.g. don't indent for `return a ? b : c`, only for `return (a ? b : c).member`
if expression.syntax() == conditional.syntax() {
return false;
}
match parent {
None => false,
Some(parent) => {
let argument = match parent.kind() {
JsSyntaxKind::JS_INITIALIZER_CLAUSE => {
let initializer = JsInitializerClause::unwrap_cast(parent);
initializer.expression().ok().map(AnyJsExpression::from)
}
JsSyntaxKind::JS_RETURN_STATEMENT => {
let return_statement = JsReturnStatement::unwrap_cast(parent);
return_statement.argument().map(AnyJsExpression::from)
}
JsSyntaxKind::JS_THROW_STATEMENT => {
let throw_statement = JsThrowStatement::unwrap_cast(parent);
throw_statement.argument().ok().map(AnyJsExpression::from)
}
JsSyntaxKind::JS_UNARY_EXPRESSION => {
let unary_expression = JsUnaryExpression::unwrap_cast(parent);
unary_expression.argument().ok().map(AnyJsExpression::from)
}
JsSyntaxKind::JS_YIELD_ARGUMENT => {
let yield_argument = JsYieldArgument::unwrap_cast(parent);
yield_argument.expression().ok().map(AnyJsExpression::from)
}
JsSyntaxKind::JS_ASSIGNMENT_EXPRESSION => {
let assignment_expression = JsAssignmentExpression::unwrap_cast(parent);
assignment_expression
.right()
.ok()
.map(AnyJsExpression::from)
}
_ => None,
};
argument.map_or(false, |argument| argument == expression)
}
}
}
/// Returns `true` if this is the root conditional expression and the parent is a [JsStaticMemberExpression].
fn is_parent_static_member_expression(
&self,
conditional: &AnyJsConditional,
layout: &ConditionalLayout,
) -> bool {
if !conditional.is_conditional_expression() {
return false;
}
match layout {
ConditionalLayout::Root {
parent: Some(parent),
..
} => JsStaticMemberExpression::can_cast(parent.kind()),
_ => false,
}
}
}
/// Formats the test conditional of a conditional expression.
struct FormatConditionalTest<'a> {
conditional: &'a AnyJsConditional,
layout: &'a ConditionalLayout,
}
impl Format<JsFormatContext> for FormatConditionalTest<'_> {
fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
let format_inner = format_with(|f| match self.conditional {
AnyJsConditional::JsConditionalExpression(conditional) => {
write!(f, [conditional.test().format()])
}
AnyJsConditional::TsConditionalType(conditional) => {
write!(
f,
[
conditional.check_type().format(),
space(),
conditional.extends_token().format(),
space(),
conditional.extends_type().format()
]
)
}
});
if self.layout.is_nested_alternate() {
align(2, &format_inner).fmt(f)
} else {
format_inner.fmt(f)
}
}
}
declare_node_union! {
ExpressionOrType = AnyJsExpression | AnyTsType
}
impl ExpressionOrType {
fn as_expression(&self) -> Option<&AnyJsExpression> {
match self {
ExpressionOrType::AnyJsExpression(expression) => Some(expression),
ExpressionOrType::AnyTsType(_) => None,
}
}
}
impl Format<JsFormatContext> for ExpressionOrType {
fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
match self {
ExpressionOrType::AnyJsExpression(expression) => expression.format().fmt(f),
ExpressionOrType::AnyTsType(ty) => ty.format().fmt(f),
}
}
}
#[derive(Clone, Eq, PartialEq, Debug)]
enum ConditionalLayout {
/// Conditional that is the `alternate` of another conditional.
///
/// The `test` condition of a nested alternated is aligned with the parent's `:`.
///
/// ```javascript
/// outerCondition
/// ? consequent
/// : nestedAlternate +
/// binary + // <- notice how the content is aligned to the `: `
/// ? consequentOfnestedAlternate
/// : alternateOfNestedAlternate;
/// ```
NestedAlternate { parent: AnyJsConditional },
/// Conditional that is the `test` of another conditional.
///
/// ```javascript
/// (
/// a // <-- Note the extra indent here
/// ? b
/// : c
/// )
/// ? d
/// : e;
/// ```
///
/// Indents the
NestedTest { parent: AnyJsConditional },
/// Conditional that is the `consequent` of another conditional.
///
/// ```javascript
/// condition1
/// ? condition2
/// ? consequent2 // <-- consequent and alternate gets indented
/// : alternate2
/// : alternate1;
/// ```
NestedConsequent { parent: AnyJsConditional },
/// This conditional isn't a child of another conditional.
///
/// ```javascript
/// return a ? b : c;
/// ```
Root {
/// The closest ancestor that isn't a parenthesized node.
parent: Option<JsSyntaxNode>,
jsx_chain: ConditionalJsxChain,
},
}
/// A [JsConditionalExpression] that itself or any of its parent's [JsConditionalExpression] have a a [JsxTagExpression]
/// as its [`test`](JsConditionalExpression::test), [`consequent`](JsConditionalExpression::consequent) or [`alternate`](JsConditionalExpression::alternate).
///
/// Parenthesizes the `consequent` and `alternate` if it the group breaks except if the expressions are
/// * `null`
/// * `undefined`
/// * or a nested [JsConditionalExpression] in the alternate branch
///
/// ```javascript
/// abcdefgh? (
/// <Element>
/// <Sub />
/// <Sub />
/// </Element>
/// ) : (
/// <Element2>
/// <Sub />
/// <Sub />
/// </Element2>
/// );
/// ```
#[derive(Copy, Clone, Eq, PartialEq, Debug, Default)]
pub enum ConditionalJsxChain {
Chain,
#[default]
NoChain,
}
impl ConditionalJsxChain {
pub const fn is_chain(&self) -> bool {
matches!(self, ConditionalJsxChain::Chain)
}
pub const fn is_no_chain(&self) -> bool {
matches!(self, ConditionalJsxChain::NoChain)
}
}
impl From<bool> for ConditionalJsxChain {
fn from(value: bool) -> Self {
match value {
true => ConditionalJsxChain::Chain,
false => ConditionalJsxChain::NoChain,
}
}
}
impl ConditionalLayout {
const fn jsx_chain(&self) -> Option<ConditionalJsxChain> {
match self {
ConditionalLayout::NestedAlternate { .. }
| ConditionalLayout::NestedTest { .. }
| ConditionalLayout::NestedConsequent { .. } => None,
ConditionalLayout::Root { jsx_chain, .. } => Some(*jsx_chain),
}
}
const fn is_root(&self) -> bool {
matches!(self, ConditionalLayout::Root { .. })
}
/// Returns the parent node, if any
fn parent(&self) -> Option<&JsSyntaxNode> {
match self {
ConditionalLayout::NestedAlternate { parent, .. }
| ConditionalLayout::NestedTest { parent, .. }
| ConditionalLayout::NestedConsequent { parent, .. } => Some(parent.syntax()),
ConditionalLayout::Root { parent, .. } => parent.as_ref(),
}
}
const fn is_nested_test(&self) -> bool {
matches!(self, ConditionalLayout::NestedTest { .. })
}
const fn is_nested_alternate(&self) -> bool {
matches!(self, ConditionalLayout::NestedAlternate { .. })
}
const fn is_nested_consequent(&self) -> bool {
matches!(self, ConditionalLayout::NestedConsequent { .. })
}
}
impl AnyJsConditional {
/// Returns `true` if `node` is the `test` of this conditional.
fn is_test(&self, node: &JsSyntaxNode) -> bool {
match self {
AnyJsConditional::JsConditionalExpression(conditional) => conditional
.test()
.ok()
.map_or(false, |resolved| resolved.syntax() == node),
AnyJsConditional::TsConditionalType(conditional) => {
conditional.check_type().map(AstNode::into_syntax).as_ref() == Ok(node)
|| conditional
.extends_type()
.map(AstNode::into_syntax)
.as_ref()
== Ok(node)
}
}
}
pub(crate) fn question_mark_token(&self) -> SyntaxResult<JsSyntaxToken> {
match self {
AnyJsConditional::JsConditionalExpression(conditional) => {
conditional.question_mark_token()
}
AnyJsConditional::TsConditionalType(conditional) => conditional.question_mark_token(),
}
}
fn consequent(&self) -> SyntaxResult<ExpressionOrType> {
match self {
AnyJsConditional::JsConditionalExpression(conditional) => {
conditional.consequent().map(ExpressionOrType::from)
}
AnyJsConditional::TsConditionalType(conditional) => {
conditional.true_type().map(ExpressionOrType::from)
}
}
}
pub(crate) fn colon_token(&self) -> SyntaxResult<JsSyntaxToken> {
match self {
AnyJsConditional::JsConditionalExpression(conditional) => conditional.colon_token(),
AnyJsConditional::TsConditionalType(conditional) => conditional.colon_token(),
}
}
fn alternate(&self) -> SyntaxResult<ExpressionOrType> {
match self {
AnyJsConditional::JsConditionalExpression(conditional) => {
conditional.alternate().map(ExpressionOrType::from)
}
AnyJsConditional::TsConditionalType(conditional) => {
conditional.false_type().map(ExpressionOrType::from)
}
}
}
/// Returns `true` if the passed node is the `alternate` of this conditional expression.
fn is_alternate(&self, node: &JsSyntaxNode) -> bool {
let alternate = match self {
AnyJsConditional::JsConditionalExpression(conditional) => {
conditional.alternate().map(AstNode::into_syntax).ok()
}
AnyJsConditional::TsConditionalType(ts_conditional) => {
ts_conditional.false_type().ok().map(AstNode::into_syntax)
}
};
alternate.as_ref() == Some(node)
}
const fn is_conditional_expression(&self) -> bool {
matches!(self, AnyJsConditional::JsConditionalExpression(_))
}
}
fn is_jsx_conditional_chain(outer_most: &JsConditionalExpression) -> bool {
fn recurse(expression: SyntaxResult<AnyJsExpression>) -> bool {
use AnyJsExpression::*;
match expression {
Ok(JsConditionalExpression(conditional)) => is_jsx_conditional_chain(&conditional),
Ok(JsxTagExpression(_)) => true,
_ => false,
}
}
recurse(outer_most.test())
|| recurse(outer_most.consequent())
|| recurse(outer_most.alternate())
}
fn format_jsx_chain_consequent(expression: &AnyJsExpression) -> FormatJsxChainExpression {
FormatJsxChainExpression {
expression,
alternate: false,
}
}
fn format_jsx_chain_alternate(alternate: &AnyJsExpression) -> FormatJsxChainExpression {
FormatJsxChainExpression {
expression: alternate,
alternate: true,
}
}
/// Wraps all expressions in parentheses if they break EXCEPT
/// * Nested conditionals in the alternate
/// * `null`
/// * `undefined`
struct FormatJsxChainExpression<'a> {
expression: &'a AnyJsExpression,
alternate: bool,
}
impl Format<JsFormatContext> for FormatJsxChainExpression<'_> {
fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
use AnyJsExpression::*;
let no_wrap = match self.expression {
JsIdentifierExpression(identifier) if identifier.name()?.is_undefined() => true,
AnyJsLiteralExpression(
rome_js_syntax::AnyJsLiteralExpression::JsNullLiteralExpression(_),
) => true,
JsConditionalExpression(_) if self.alternate => true,
_ => false,
};
let format_expression = format_with(|f| match self.expression {
JsConditionalExpression(conditional) => {
write!(
f,
[conditional
.format()
.with_options(ConditionalJsxChain::Chain)]
)
}
expression => {
write!(f, [expression.format()])
}
});
if no_wrap {
write!(f, [format_expression])
} else {
write!(
f,
[
if_group_breaks(&text("(")),
soft_block_indent(&format_expression),
if_group_breaks(&text(")"))
]
)
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/utils/jsx.rs | crates/rome_js_formatter/src/utils/jsx.rs | use crate::context::QuoteStyle;
use crate::prelude::*;
use crate::JsCommentStyle;
use rome_formatter::{comments::CommentStyle, format_args, write};
use rome_js_syntax::{
AnyJsExpression, AnyJsLiteralExpression, AnyJsxChild, AnyJsxTag, JsComputedMemberExpression,
JsStaticMemberExpression, JsSyntaxKind, JsxChildList, JsxExpressionChild, JsxTagExpression,
JsxText, TextLen,
};
use rome_rowan::{Direction, SyntaxResult, TextRange, TextSize, TokenText};
use std::iter::{FusedIterator, Peekable};
use std::str::Chars;
pub(crate) static JSX_WHITESPACE_CHARS: [char; 4] = [' ', '\n', '\t', '\r'];
/// Meaningful JSX text is defined to be text that has either non-whitespace
/// characters, or does not contain a newline. Whitespace is defined as ASCII
/// whitespace.
///
/// ```
/// use rome_js_formatter::utils::jsx::is_meaningful_jsx_text;
///
/// assert_eq!(is_meaningful_jsx_text(" \t\r "), true);
/// assert_eq!(is_meaningful_jsx_text(" \n\r "), false);
/// assert_eq!(is_meaningful_jsx_text(" Alien "), true);
/// assert_eq!(is_meaningful_jsx_text("\n Alien "), true);
/// assert_eq!(is_meaningful_jsx_text(" Alien \n"), true);
/// assert_eq!(is_meaningful_jsx_text(""), true);
/// ```
pub fn is_meaningful_jsx_text(text: &str) -> bool {
let mut has_newline = false;
for c in text.chars() {
// If there is a non-whitespace character
if !JSX_WHITESPACE_CHARS.contains(&c) {
return true;
} else if c == '\n' {
has_newline = true;
}
}
!has_newline
}
/// Tests if a [JsxAnyTag] has a suppression comment or not.
///
/// Suppression for [JsxAnyTag] differs from regular nodes if they are inside of a [JsxChildList] because
/// they can then not be preceded by a comment.
///
/// A [JsxAnyTag] inside of a [JsxChildList] is suppressed if its first preceding sibling (that contains meaningful text)
/// is a [JsxExpressionChild], not containing any expression, with a dangling suppression comment.
///
/// ```javascript
/// <div>
// {/* rome-ignore format: reason */}
// <div a={ some} />
// </div>
/// ```
pub(crate) fn is_jsx_suppressed(tag: &AnyJsxTag, comments: &JsComments) -> bool {
comments.mark_suppression_checked(tag.syntax());
match tag.parent::<JsxChildList>() {
Some(_) => {
let prev_non_empty_text_sibling =
tag.syntax()
.siblings(Direction::Prev)
.skip(1)
.find(|sibling| {
if let Some(text) = JsxText::cast_ref(sibling) {
text.value_token()
.map_or(true, |token| is_meaningful_jsx_text(token.text()))
} else {
true
}
});
match prev_non_empty_text_sibling.and_then(JsxExpressionChild::cast) {
Some(child) if child.expression().is_none() => comments
.dangling_comments(child.syntax())
.iter()
.any(|comment| JsCommentStyle::is_suppression(comment.piece().text())),
Some(_) | None => false,
}
}
_ => false,
}
}
/// Indicates that an element should always be wrapped in parentheses, should be wrapped
/// only when it's line broken, or should not be wrapped at all.
#[derive(Copy, Clone, Debug)]
pub(crate) enum WrapState {
/// For a JSX element that is never wrapped in parentheses.
/// For instance, a JSX element that is another element's attribute
/// should never be wrapped:
/// ```jsx
/// <Route path="/" component={<HomePage />} />
/// ```
NoWrap,
/// For a JSX element that must be wrapped in parentheses when line broken.
/// For instance, a JSX element nested in a let binding is wrapped on line break:
/// ```jsx
/// let component = <div> La Haine dir. Mathieu Kassovitz </div>;
///
/// let component = (
/// <div> Uncle Boonmee Who Can Recall His Past Lives dir. Apichatpong Weerasethakul </div>
/// );
/// ```
WrapOnBreak,
}
/// Checks if a JSX Element should be wrapped in parentheses. Returns a [WrapState] which
/// indicates when the element should be wrapped in parentheses.
pub(crate) fn get_wrap_state(node: &JsxTagExpression) -> WrapState {
// We skip the first item because the first item in ancestors is the node itself, i.e.
// the JSX Element in this case.
let parent = node.syntax().parent();
parent.map_or(WrapState::NoWrap, |parent| match parent.kind() {
JsSyntaxKind::JS_ARRAY_ELEMENT_LIST
| JsSyntaxKind::JSX_ATTRIBUTE
| JsSyntaxKind::JSX_EXPRESSION_ATTRIBUTE_VALUE
| JsSyntaxKind::JSX_EXPRESSION_CHILD
| JsSyntaxKind::JS_EXPRESSION_STATEMENT
| JsSyntaxKind::JS_CALL_ARGUMENT_LIST
| JsSyntaxKind::JS_EXPRESSION_SNIPPED
| JsSyntaxKind::JS_CONDITIONAL_EXPRESSION => WrapState::NoWrap,
JsSyntaxKind::JS_STATIC_MEMBER_EXPRESSION => {
let member = JsStaticMemberExpression::unwrap_cast(parent);
if member.is_optional_chain() {
WrapState::NoWrap
} else {
WrapState::WrapOnBreak
}
}
JsSyntaxKind::JS_COMPUTED_MEMBER_EXPRESSION => {
let member = JsComputedMemberExpression::unwrap_cast(parent);
if member.is_optional_chain() {
WrapState::NoWrap
} else {
WrapState::WrapOnBreak
}
}
_ => WrapState::WrapOnBreak,
})
}
/// Creates either a space using an expression child and a string literal,
/// or a regular space, depending on whether the group breaks or not.
///
/// ```jsx
/// <div> Winter Light </div>;
///
/// <div>
/// {" "}Winter Light
/// Through A Glass Darkly
/// The Silence
/// Seventh Seal
/// Wild Strawberries
/// </div>
/// ```
#[derive(Default)]
pub(crate) struct JsxSpace;
impl Format<JsFormatContext> for JsxSpace {
fn fmt(&self, formatter: &mut JsFormatter) -> FormatResult<()> {
write![
formatter,
[
if_group_breaks(&format_args![JsxRawSpace, soft_line_break()]),
if_group_fits_on_line(&space())
]
]
}
}
pub(crate) struct JsxRawSpace;
impl Format<JsFormatContext> for JsxRawSpace {
fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
let jsx_space = match f.options().quote_style() {
QuoteStyle::Double => r#"{" "}"#,
QuoteStyle::Single => "{' '}",
};
write!(f, [text(jsx_space)])
}
}
pub(crate) fn is_whitespace_jsx_expression(
child: &JsxExpressionChild,
comments: &JsComments,
) -> bool {
match child.expression() {
Some(AnyJsExpression::AnyJsLiteralExpression(
AnyJsLiteralExpression::JsStringLiteralExpression(literal),
)) => {
match (
child.l_curly_token(),
literal.value_token(),
child.r_curly_token(),
) {
(Ok(_), Ok(value_token), Ok(r_curly_token)) => {
let is_empty = matches!(value_token.text_trimmed(), "\" \"" | "' '");
let has_comments = comments.has_skipped(&r_curly_token)
|| comments.has_comments(literal.syntax());
is_empty && !has_comments
}
_ => false,
}
}
_ => false,
}
}
pub(crate) fn jsx_split_children<I>(
children: I,
comments: &JsComments,
) -> SyntaxResult<Vec<JsxChild>>
where
I: IntoIterator<Item = AnyJsxChild>,
{
let mut builder = JsxSplitChildrenBuilder::new();
for child in children.into_iter() {
match child {
AnyJsxChild::JsxText(text) => {
// Split the text into words
// Keep track if there's any leading/trailing empty line, new line or whitespace
let value_token = text.value_token()?;
let mut chunks = JsxSplitChunksIterator::new(value_token.text()).peekable();
// Text starting with a whitespace
if let Some((_, JsxTextChunk::Whitespace(_whitespace))) = chunks.peek() {
match chunks.next() {
Some((_, JsxTextChunk::Whitespace(whitespace))) => {
if whitespace.contains('\n') {
if chunks.peek().is_none() {
// A text only consisting of whitespace that also contains a new line isn't considered meaningful text.
// It can be entirely removed from the content without changing the semantics.
let newlines =
whitespace.chars().filter(|c| *c == '\n').count();
// Keep up to one blank line between tags/expressions and text.
// ```javascript
// <div>
//
// <MyElement />
// </div>
// ```
if newlines > 1 {
builder.entry(JsxChild::EmptyLine);
}
continue;
}
builder.entry(JsxChild::Newline)
} else {
builder.entry(JsxChild::Whitespace)
}
}
_ => unreachable!(),
}
}
while let Some(chunk) = chunks.next() {
match chunk {
(_, JsxTextChunk::Whitespace(whitespace)) => {
// Only handle trailing whitespace. Words must always be joined by new lines
if chunks.peek().is_none() {
if whitespace.contains('\n') {
builder.entry(JsxChild::Newline);
} else {
builder.entry(JsxChild::Whitespace)
}
}
}
(relative_start, JsxTextChunk::Word(word)) => {
let text = value_token
.token_text()
.slice(TextRange::at(relative_start, word.text_len()));
let source_position = value_token.text_range().start() + relative_start;
builder.entry(JsxChild::Word(JsxWord::new(text, source_position)));
}
}
}
}
AnyJsxChild::JsxExpressionChild(child) => {
if is_whitespace_jsx_expression(&child, comments) {
builder.entry(JsxChild::Whitespace)
} else {
builder.entry(JsxChild::NonText(child.into()))
}
}
child => {
builder.entry(JsxChild::NonText(child));
}
}
}
Ok(builder.finish())
}
/// The builder is used to:
/// 1. Remove [JsxChild::EmptyLine], [JsxChild::Newline], [JsxChild::Whitespace] if a next element is [JsxChild::Whitespace]
/// 2. Don't push a new element [JsxChild::EmptyLine], [JsxChild::Newline], [JsxChild::Whitespace] if previous one is [JsxChild::EmptyLine], [JsxChild::Newline], [JsxChild::Whitespace]
/// [Prettier applies]: https://github.com/prettier/prettier/blob/b0d9387b95cdd4e9d50f5999d3be53b0b5d03a97/src/language-js/print/jsx.js#L144-L180
#[derive(Debug)]
struct JsxSplitChildrenBuilder {
buffer: Vec<JsxChild>,
}
impl JsxSplitChildrenBuilder {
fn new() -> Self {
JsxSplitChildrenBuilder { buffer: vec![] }
}
fn entry(&mut self, child: JsxChild) {
match self.buffer.last_mut() {
Some(last @ (JsxChild::EmptyLine | JsxChild::Newline | JsxChild::Whitespace)) => {
if matches!(child, JsxChild::Whitespace) {
*last = child;
} else if matches!(child, JsxChild::NonText(_) | JsxChild::Word(_)) {
self.buffer.push(child);
}
}
_ => self.buffer.push(child),
}
}
fn finish(self) -> Vec<JsxChild> {
self.buffer
}
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub(crate) enum JsxChild {
/// A Single word in a JSX text. For example, the words for `a b\nc` are `[a, b, c]`
Word(JsxWord),
/// A ` ` or `${" "}` whitespace
///
/// ```javascript
/// <div> </div>
/// <div>a </div>
/// <div> a</div>
/// <div>{' '}a</div>
/// <div>a{' '}</div>
/// <div>{' '}</div>
/// <div>a
/// {' '}b</div>
/// ```
///
/// Whitespace between two words is not represented as whitespace
/// ```javascript
/// <div>a b</div>
/// ```
/// The space between `a` and `b` is not considered a whitespace.
Whitespace,
/// A new line at the start or end of a [JsxText] with meaningful content. (that isn't all whitespace
/// and contains a new line).
///
/// ```javascript
/// <div>
/// a
/// </div>
/// ```
Newline,
/// A [JsxText] that only consists of whitespace and has at least two line breaks;
///
/// ```javascript
/// <div>
///
/// <test />
/// </div>
/// ```
///
/// The text between `<div>` and `<test />` is an empty line text.
EmptyLine,
/// Any other content that isn't a text. Should be formatted as is.
NonText(AnyJsxChild),
}
impl JsxChild {
pub(crate) const fn is_any_line(&self) -> bool {
matches!(self, JsxChild::EmptyLine | JsxChild::Newline)
}
}
/// A word in a Jsx Text. A word is string sequence that isn't separated by any JSX whitespace.
#[derive(Debug, Clone, Eq, PartialEq)]
pub(crate) struct JsxWord {
text: TokenText,
source_position: TextSize,
}
impl JsxWord {
fn new(text: TokenText, source_position: TextSize) -> Self {
JsxWord {
text,
source_position,
}
}
pub(crate) fn is_ascii_punctuation(&self) -> bool {
self.text.chars().count() == 1
&& self
.text
.chars()
.next()
.map_or(false, |char| char.is_ascii_punctuation())
}
}
impl Format<JsFormatContext> for JsxWord {
fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
f.write_element(FormatElement::LocatedTokenText {
source_position: self.source_position,
slice: self.text.clone(),
})
}
}
#[derive(Eq, PartialEq, Copy, Clone, Debug)]
enum JsxTextChunk<'a> {
Whitespace(&'a str),
Word(&'a str),
}
/// Splits a text into whitespace only and non-whitespace chunks.
///
/// See `jsx_split_chunks_iterator` test for examples
struct JsxSplitChunksIterator<'a> {
position: TextSize,
text: &'a str,
chars: Peekable<Chars<'a>>,
}
impl<'a> JsxSplitChunksIterator<'a> {
fn new(text: &'a str) -> Self {
Self {
position: TextSize::default(),
text,
chars: text.chars().peekable(),
}
}
}
impl<'a> Iterator for JsxSplitChunksIterator<'a> {
type Item = (TextSize, JsxTextChunk<'a>);
fn next(&mut self) -> Option<Self::Item> {
let char = self.chars.next()?;
let start = self.position;
self.position += char.text_len();
let is_whitespace = matches!(char, ' ' | '\n' | '\t' | '\r');
while let Some(next) = self.chars.peek() {
let next_is_whitespace = matches!(next, ' ' | '\n' | '\t' | '\r');
if is_whitespace != next_is_whitespace {
break;
}
self.position += next.text_len();
self.chars.next();
}
let range = TextRange::new(start, self.position);
let slice = &self.text[range];
let chunk = if is_whitespace {
JsxTextChunk::Whitespace(slice)
} else {
JsxTextChunk::Word(slice)
};
Some((start, chunk))
}
}
impl FusedIterator for JsxSplitChunksIterator<'_> {}
/// An iterator adaptor that allows a lookahead of two tokens
///
/// # Examples
/// ```
/// use rome_js_formatter::utils::jsx::JsxChildrenIterator;
///
/// let buffer = vec![1, 2, 3, 4];
///
/// let mut iter = JsxChildrenIterator::new(buffer.iter());
///
/// assert_eq!(iter.peek(), Some(&&1));
/// assert_eq!(iter.peek_next(), Some(&&2));
/// assert_eq!(iter.next(), Some(&1));
/// assert_eq!(iter.next(), Some(&2));
/// ```
#[derive(Clone, Debug)]
pub struct JsxChildrenIterator<I: Iterator> {
iter: I,
peeked: Option<Option<I::Item>>,
peeked_next: Option<Option<I::Item>>,
}
impl<I: Iterator> JsxChildrenIterator<I> {
pub fn new(iter: I) -> Self {
Self {
iter,
peeked: None,
peeked_next: None,
}
}
pub fn peek(&mut self) -> Option<&I::Item> {
let iter = &mut self.iter;
self.peeked.get_or_insert_with(|| iter.next()).as_ref()
}
pub fn peek_next(&mut self) -> Option<&I::Item> {
let iter = &mut self.iter;
let peeked = &mut self.peeked;
self.peeked_next
.get_or_insert_with(|| {
peeked.get_or_insert_with(|| iter.next());
iter.next()
})
.as_ref()
}
}
impl<I: Iterator> Iterator for JsxChildrenIterator<I> {
type Item = I::Item;
fn next(&mut self) -> Option<Self::Item> {
match self.peeked.take() {
Some(peeked) => {
self.peeked = self.peeked_next.take();
peeked
}
None => self.iter.next(),
}
}
}
#[cfg(test)]
mod tests {
use crate::utils::jsx::{
jsx_split_children, JsxChild, JsxChildrenIterator, JsxSplitChunksIterator, JsxTextChunk,
};
use rome_formatter::comments::Comments;
use rome_js_parser::{parse, JsParserOptions};
use rome_js_syntax::{JsFileSource, JsxChildList, JsxText};
use rome_rowan::{AstNode, TextSize};
#[test]
fn jsx_children_iterator_test() {
let buffer = vec![1, 2, 3, 4];
let mut iter = JsxChildrenIterator::new(buffer.iter());
assert_eq!(iter.peek(), Some(&&1));
assert_eq!(iter.peek(), Some(&&1));
assert_eq!(iter.peek_next(), Some(&&2));
assert_eq!(iter.peek_next(), Some(&&2));
assert_eq!(iter.next(), Some(&1));
assert_eq!(iter.next(), Some(&2));
assert_eq!(iter.peek_next(), Some(&&4));
assert_eq!(iter.peek_next(), Some(&&4));
assert_eq!(iter.peek(), Some(&&3));
assert_eq!(iter.peek(), Some(&&3));
}
fn assert_jsx_text_chunks(text: &str, expected_chunks: Vec<(TextSize, JsxTextChunk)>) {
let parse = parse(
&std::format!("<>{text}</>"),
JsFileSource::jsx(),
JsParserOptions::default(),
);
assert!(
!parse.has_errors(),
"Source should not have any errors {:?}",
parse.diagnostics()
);
let jsx_text = parse
.syntax()
.descendants()
.find_map(JsxText::cast)
.expect("Expected a JSX Text child");
let value_token = jsx_text.value_token().unwrap();
let chunks = JsxSplitChunksIterator::new(value_token.text()).collect::<Vec<_>>();
assert_eq!(chunks, expected_chunks);
}
#[test]
fn jsx_split_chunks_iterator() {
assert_jsx_text_chunks(
"a b c",
vec![
(TextSize::from(0), JsxTextChunk::Word("a")),
(TextSize::from(1), JsxTextChunk::Whitespace(" ")),
(TextSize::from(2), JsxTextChunk::Word("b")),
(TextSize::from(3), JsxTextChunk::Whitespace(" ")),
(TextSize::from(4), JsxTextChunk::Word("c")),
],
);
// merges consequent spaces
assert_jsx_text_chunks(
"a\n\rb",
vec![
(TextSize::from(0), JsxTextChunk::Word("a")),
(TextSize::from(1), JsxTextChunk::Whitespace("\n\r")),
(TextSize::from(3), JsxTextChunk::Word("b")),
],
);
// merges consequent non whitespace characters
assert_jsx_text_chunks(
"abcd efg",
vec![
(TextSize::from(0), JsxTextChunk::Word("abcd")),
(TextSize::from(4), JsxTextChunk::Whitespace(" ")),
(TextSize::from(5), JsxTextChunk::Word("efg")),
],
);
// whitespace at the beginning
assert_jsx_text_chunks(
"\n\n abcd",
vec![
(TextSize::from(0), JsxTextChunk::Whitespace("\n\n ")),
(TextSize::from(3), JsxTextChunk::Word("abcd")),
],
);
// whitespace at the end
assert_jsx_text_chunks(
"abcd \n\n",
vec![
(TextSize::from(0), JsxTextChunk::Word("abcd")),
(TextSize::from(4), JsxTextChunk::Whitespace(" \n\n")),
],
);
}
fn parse_jsx_children(children: &str) -> JsxChildList {
let parse = parse(
&std::format!("<div>{children}</div>"),
JsFileSource::jsx(),
JsParserOptions::default(),
);
assert!(
!parse.has_errors(),
"Expected source text to not have any errors: {:?}",
parse.diagnostics()
);
parse
.syntax()
.descendants()
.find_map(JsxChildList::cast)
.expect("Expect a JsxChildList")
}
#[test]
fn split_children_words_only() {
let child_list = parse_jsx_children("a b c");
let children = jsx_split_children(&child_list, &Comments::default()).unwrap();
assert_eq!(3, children.len());
assert_word(&children[0], "a");
assert_word(&children[1], "b");
assert_word(&children[2], "c");
}
#[test]
fn split_non_meaningful_text() {
let child_list = parse_jsx_children(" \n ");
let children = jsx_split_children(&child_list, &Comments::default()).unwrap();
assert_eq!(children, vec![]);
}
#[test]
fn split_non_meaningful_leading_multiple_lines() {
let child_list = parse_jsx_children(" \n \n ");
let children = jsx_split_children(&child_list, &Comments::default()).unwrap();
assert_eq!(children, vec![JsxChild::EmptyLine]);
}
#[test]
fn split_meaningful_whitespace() {
let child_list = parse_jsx_children(" ");
let children = jsx_split_children(&child_list, &Comments::default()).unwrap();
assert_eq!(children, vec![JsxChild::Whitespace]);
}
#[test]
fn split_children_leading_newlines() {
let child_list = parse_jsx_children(" \n a b");
let children = jsx_split_children(&child_list, &Comments::default()).unwrap();
assert_eq!(3, children.len());
assert_eq!(children[0], JsxChild::Newline);
assert_word(&children[1], "a");
assert_word(&children[2], "b");
}
#[test]
fn split_children_trailing_whitespace() {
let child_list = parse_jsx_children("a b \t ");
let children = jsx_split_children(&child_list, &Comments::default()).unwrap();
assert_eq!(3, children.len());
assert_word(&children[0], "a");
assert_word(&children[1], "b");
assert_eq!(children[2], JsxChild::Whitespace);
}
#[test]
fn split_children_trailing_newline() {
let child_list = parse_jsx_children("a b \n \t ");
let children = jsx_split_children(&child_list, &Comments::default()).unwrap();
assert_eq!(3, children.len());
assert_word(&children[0], "a");
assert_word(&children[1], "b");
assert_eq!(children[2], JsxChild::Newline);
}
#[test]
fn split_children_empty_expression() {
let child_list = parse_jsx_children(r#"a{' '}c{" "}"#);
let children = jsx_split_children(&child_list, &Comments::default()).unwrap();
assert_eq!(
4,
children.len(),
"Expected to contain four elements. Actual:\n{children:#?} "
);
assert_word(&children[0], "a");
assert_eq!(children[1], JsxChild::Whitespace);
assert_word(&children[2], "c");
assert_eq!(children[3], JsxChild::Whitespace);
}
#[test]
fn split_children_remove_in_row_jsx_whitespaces() {
let child_list = parse_jsx_children(r#"a{' '}{' '}{' '}c{" "}{' '}{" "}"#);
let children = jsx_split_children(&child_list, &Comments::default()).unwrap();
assert_eq!(
4,
children.len(),
"Expected to contain four elements. Actual:\n{children:#?} "
);
assert_word(&children[0], "a");
assert_eq!(children[1], JsxChild::Whitespace);
assert_word(&children[2], "c");
assert_eq!(children[3], JsxChild::Whitespace);
}
#[test]
fn split_children_remove_new_line_before_jsx_whitespaces() {
let child_list = parse_jsx_children(
r#"a
{' '}c{" "}
"#,
);
let children = jsx_split_children(&child_list, &Comments::default()).unwrap();
assert_eq!(
4,
children.len(),
"Expected to contain four elements. Actual:\n{children:#?} "
);
assert_word(&children[0], "a");
assert_eq!(children[1], JsxChild::Whitespace);
assert_word(&children[2], "c");
assert_eq!(children[3], JsxChild::Whitespace);
}
fn assert_word(child: &JsxChild, text: &str) {
match child {
JsxChild::Word(word) => {
assert_eq!(word.text.text(), text)
}
child => {
panic!("Expected a word but found {child:#?}");
}
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/utils/binary_like_expression.rs | crates/rome_js_formatter/src/utils/binary_like_expression.rs | //! This module implements the formatting of binary like nodes. Binary like nodes are nodes with
//! `left` and `right` expressions. Today, this includes:
//! * [JsBinaryExpression]
//! * [JsLogicalExpression]
//! * [JsInExpression]
//! * [JsInstanceofExpression]
//!
//! The challenge of formatting binary like expressions is that we want to format binary expression
//! chains, when possible, together but they are represented as a deep structured tree in the CST.
//!
//! For example,
//!
//! ```js
//! some && thing && elsewhere || happy
//! ```
//!
//! Is parsed as
//!
//! ```block
//! JsLogicalExpression {
//! left: JsLogicalExpression {
//! left: JsLogicalExpression {
//! left: "some"
//! operator: "&&",
//! right: "thing"
//! }
//! operator: "&&"
//! right: "elsewhere"
//! }
//! operator: "||"
//! right: "happy"
//! }
//! ```
//!
//! The goal is to format all the left and right sides together that don't require parentheses (mainly comes down to whether the parent and its left side's operator have the same precedence).
//!
//! This is achieved by traversing down the left side of a binary expression until it reaches the first expression that can't be flattened.
//! For `some && thing && elsewhere || happy`, the implementation checks if the first left-side `some && thing && elsewhere` can be grouped.
//! This isn't the case because the left side operator `&&` differs from the parent's `||` operator.
//!
//! That means, we found the end of the first `group` and the left-side of the group is `some && thing && elsewhere`.
//! The algorithm traverses upwards and adds all right-sides of the parent binary like expressions to the group until it reaches the root.
//! In the example, this only is the `|| happy`.
//!
//! Thus, the first group is: `[Left(some && thing && elsewhere), Right(|| happy)]`. The formatting formats the left side
//! as is (the call will recurse into the [AnyJsBinaryLikeExpression] formatting again) but formats the operator with the right side.
//!
//! Now, let's see how the implementation groups the `some && thing && elsewhere`. It first traverses to the left most binary like expression,
//! which is `some && thing`. It then adds this as a `Left` side to the group. From here, the algorithm traverses upwards and adds all right sides
//! of the binary expression. These are: `&& thing` and `&& elsewhere`.
//! The complete group is: `[Left(some), Right(&& thing), Right(&& elsewhere)]`.
//!
//! Each side in the group gets formatted in order, starting with the left, then formatting the operator
//! and right side of each Right side.
use crate::prelude::*;
use rome_formatter::{format_args, write, Buffer, CstFormatContext};
use rome_js_syntax::{
AnyJsExpression, AnyJsInProperty, JsBinaryExpression, JsBinaryOperator, JsDoWhileStatement,
JsIfStatement, JsInExpression, JsInstanceofExpression, JsLogicalExpression, JsLogicalOperator,
JsPrivateName, JsSwitchStatement, JsSyntaxKind, JsSyntaxNode, JsSyntaxToken, JsUnaryExpression,
JsWhileStatement, OperatorPrecedence,
};
use crate::parentheses::{
is_arrow_function_body, is_callee, is_member_object, is_spread, is_tag, NeedsParentheses,
};
use crate::js::expressions::static_member_expression::AnyJsStaticMemberLike;
use rome_rowan::{declare_node_union, AstNode, SyntaxResult};
use std::fmt::Debug;
use std::hash::Hash;
use std::iter::FusedIterator;
declare_node_union! {
pub(crate) AnyJsBinaryLikeExpression = JsLogicalExpression | JsBinaryExpression | JsInstanceofExpression | JsInExpression
}
impl Format<JsFormatContext> for AnyJsBinaryLikeExpression {
fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
let parent = self.syntax().parent();
let is_inside_condition = self.is_inside_condition(parent.as_ref());
let parts = split_into_left_and_right_sides(self, is_inside_condition)?;
// Don't indent inside of conditions because conditions add their own indent and grouping.
if is_inside_condition {
return write!(f, [&format_once(|f| { f.join().entries(parts).finish() })]);
}
if let Some(parent) = parent.as_ref() {
// Add a group with a soft block indent in cases where it is necessary to parenthesize the binary expression.
// For example, `(a+b)(call)`, `!(a + b)`, `(a + b).test`.
if is_callee(self.syntax(), parent)
|| JsUnaryExpression::can_cast(parent.kind())
|| AnyJsStaticMemberLike::can_cast(parent.kind())
{
return write!(
f,
[group(&soft_block_indent(&format_once(|f| {
f.join().entries(parts).finish()
})))]
);
}
}
let should_not_indent = self.should_not_indent_if_parent_indents(parent.as_ref());
let inline_logical_expression = self.should_inline_logical_expression();
let should_indent_if_inlines = should_indent_if_parent_inlines(parent.as_ref());
let flattened = parts.len() > 2;
if should_not_indent
|| (inline_logical_expression && !flattened)
|| (!inline_logical_expression && should_indent_if_inlines)
{
return write!(
f,
[group(&format_once(|f| {
f.join().entries(parts).finish()
}))]
);
}
if let Some(first) = parts.first() {
let last_is_jsx = parts.last().map_or(false, |part| part.is_jsx());
let tail_parts = if last_is_jsx {
&parts[1..parts.len() - 1]
} else {
&parts[1..]
};
let group_id = f.group_id("logicalChain");
let format_non_jsx_parts = format_with(|f| {
write!(
f,
[group(&format_args![
first,
indent(&format_once(|f| {
f.join().entries(tail_parts.iter()).finish()
}))
])
.with_group_id(Some(group_id))]
)
});
if last_is_jsx {
// SAFETY: `last_is_jsx` is only true if parts is not empty
let jsx_element = parts.last().unwrap();
write!(
f,
[group(&format_args![
format_non_jsx_parts,
indent_if_group_breaks(&jsx_element, group_id),
])]
)
} else {
write!(f, [format_non_jsx_parts])
}
} else {
// Empty, should never ever happen but let's gracefully recover.
Ok(())
}
}
}
/// Creates a [BinaryLeftOrRightSide::Left] for the first left hand side that:
/// * isn't a [JsBinaryLikeExpression]
/// * is a [JsBinaryLikeExpression] but it should be formatted as its own group (see [AnyJsBinaryLikeExpression::can_flatten]).
///
/// It then traverses upwards from the left most node and creates [BinaryLikeLeftOrRightSide::Right]s for
/// every [JsBinaryLikeExpression] until it reaches the root again.
fn split_into_left_and_right_sides(
root: &AnyJsBinaryLikeExpression,
inside_condition: bool,
) -> SyntaxResult<Vec<BinaryLeftOrRightSide>> {
// Stores the left and right parts of the binary expression in sequence (rather than nested as they
// appear in the tree).
let mut items = Vec::new();
let mut expressions = BinaryLikePreorder::new(root.clone());
while let Some(event) = expressions.next() {
match event {
VisitEvent::Enter(binary) => {
if !binary.can_flatten()? {
// Stop at this expression. This is either not a binary expression OR it has
// different precedence and needs to be grouped separately.
// Calling skip_subtree prevents the exit event being triggered for this event.
expressions.skip_subtree();
items.push(BinaryLeftOrRightSide::Left { parent: binary });
}
}
VisitEvent::Exit(expression) => items.push(BinaryLeftOrRightSide::Right {
print_parent_comments: expression.syntax() != root.syntax(),
parent: expression,
inside_condition,
}),
}
}
Ok(items)
}
fn should_flatten(parent_operator: BinaryLikeOperator, operator: BinaryLikeOperator) -> bool {
if operator.precedence() != parent_operator.precedence() {
return false;
}
match (parent_operator.precedence(), operator.precedence()) {
// `**` is right associative
(OperatorPrecedence::Exponential, _) => false,
// `a == b == c` => `(a == b) == c`
(OperatorPrecedence::Equality, OperatorPrecedence::Equality) => false,
(OperatorPrecedence::Multiplicative, OperatorPrecedence::Multiplicative) => {
// `a * 3 % 5` -> `(a * 3) % 5`
if parent_operator == BinaryLikeOperator::Binary(JsBinaryOperator::Remainder)
|| operator == BinaryLikeOperator::Binary(JsBinaryOperator::Remainder)
{
false
}
// `a * 3 / 5` -> `(a * 3) / 5
else {
parent_operator == operator
}
}
// `a << 3 << 4` -> `(a << 3) << 4`
(OperatorPrecedence::Shift, OperatorPrecedence::Shift) => false,
_ => true,
}
}
/// There are cases where the parent decides to inline the the element; in
/// these cases the decide to actually break on a new line and indent it.
///
/// This function checks what the parents adheres to this behaviour
fn should_indent_if_parent_inlines(parent: Option<&JsSyntaxNode>) -> bool {
parent.map_or(false, |parent| match parent.kind() {
JsSyntaxKind::JS_ASSIGNMENT_EXPRESSION | JsSyntaxKind::JS_PROPERTY_OBJECT_MEMBER => true,
JsSyntaxKind::JS_INITIALIZER_CLAUSE => parent.parent().map_or(false, |grand_parent| {
matches!(
grand_parent.kind(),
JsSyntaxKind::JS_VARIABLE_DECLARATOR | JsSyntaxKind::JS_PROPERTY_CLASS_MEMBER
)
}),
_ => false,
})
}
/// Represents the right or left hand side of a binary expression.
#[derive(Debug, Clone)]
enum BinaryLeftOrRightSide {
/// A terminal left hand side of a binary expression.
///
/// Formats the left hand side only.
Left { parent: AnyJsBinaryLikeExpression },
/// The right hand side of a binary expression.
/// Formats the operand together with the right hand side.
Right {
parent: AnyJsBinaryLikeExpression,
/// Is the parent the condition of a `if` / `while` / `do-while` / `for` statement?
inside_condition: bool,
/// Indicates if the comments of the parent should be printed or not.
/// Must be true if `parent` isn't the root `JsAnyBinaryLike` for which `format` is called.
print_parent_comments: bool,
},
}
impl BinaryLeftOrRightSide {
#[allow(unused)]
fn is_jsx(&self) -> bool {
match self {
BinaryLeftOrRightSide::Left { parent, .. } => matches!(
parent.left(),
Ok(AnyJsBinaryLikeLeftExpression::AnyJsExpression(
AnyJsExpression::JsxTagExpression(_),
))
),
BinaryLeftOrRightSide::Right { parent, .. } => {
matches!(parent.right(), Ok(AnyJsExpression::JsxTagExpression(_)))
}
}
}
}
impl Format<JsFormatContext> for BinaryLeftOrRightSide {
fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
match self {
BinaryLeftOrRightSide::Left { parent } => {
write!(f, [group(&parent.left())])
}
BinaryLeftOrRightSide::Right {
parent: binary_like_expression,
inside_condition: inside_parenthesis,
print_parent_comments,
} => {
// It's only possible to suppress the formatting of the whole binary expression formatting OR
// the formatting of the right hand side value but not of a nested binary expression.
// This aligns with Prettier's behaviour.
f.context()
.comments()
.mark_suppression_checked(binary_like_expression.syntax());
let right = binary_like_expression.right()?;
let operator_token = binary_like_expression.operator_token()?;
let operator_and_right_expression = format_with(|f| {
let should_inline = binary_like_expression.should_inline_logical_expression();
write!(f, [space(), operator_token.format()])?;
if should_inline {
write!(f, [space()])?;
} else {
write!(f, [soft_line_break_or_space()])?;
}
write!(f, [right.format()])?;
Ok(())
});
let syntax = binary_like_expression.syntax();
let parent = syntax.parent();
// Doesn't match prettier that only distinguishes between logical and binary
let parent_has_same_kind = parent.as_ref().map_or(false, |parent| {
is_same_binary_expression_kind(binary_like_expression, parent)
});
let left_has_same_kind = binary_like_expression
.left()?
.into_expression()
.map_or(false, |left| {
is_same_binary_expression_kind(binary_like_expression, left.syntax())
});
let right_has_same_kind =
is_same_binary_expression_kind(binary_like_expression, right.syntax());
let should_break = f
.context()
.comments()
.trailing_comments(binary_like_expression.left()?.syntax())
.iter()
.any(|comment| comment.kind().is_line());
let should_group = !(parent_has_same_kind
|| left_has_same_kind
|| right_has_same_kind
|| (*inside_parenthesis
&& matches!(
binary_like_expression,
AnyJsBinaryLikeExpression::JsLogicalExpression(_)
)));
if *print_parent_comments {
write!(
f,
[format_leading_comments(binary_like_expression.syntax())]
)?;
}
if should_group {
write!(
f,
[group(&operator_and_right_expression).should_expand(should_break)]
)?;
} else {
write!(f, [operator_and_right_expression])?;
}
if *print_parent_comments {
write!(
f,
[format_trailing_comments(binary_like_expression.syntax())]
)?;
}
Ok(())
}
}
}
}
impl AnyJsBinaryLikeExpression {
pub(crate) fn left(&self) -> SyntaxResult<AnyJsBinaryLikeLeftExpression> {
match self {
AnyJsBinaryLikeExpression::JsLogicalExpression(logical) => logical
.left()
.map(AnyJsBinaryLikeLeftExpression::AnyJsExpression),
AnyJsBinaryLikeExpression::JsBinaryExpression(binary) => binary
.left()
.map(AnyJsBinaryLikeLeftExpression::AnyJsExpression),
AnyJsBinaryLikeExpression::JsInstanceofExpression(instanceof) => instanceof
.left()
.map(AnyJsBinaryLikeLeftExpression::AnyJsExpression),
AnyJsBinaryLikeExpression::JsInExpression(in_expression) => in_expression
.property()
.map(AnyJsBinaryLikeLeftExpression::from),
}
}
fn operator_token(&self) -> SyntaxResult<JsSyntaxToken> {
match self {
AnyJsBinaryLikeExpression::JsLogicalExpression(logical) => logical.operator_token(),
AnyJsBinaryLikeExpression::JsBinaryExpression(binary) => binary.operator_token(),
AnyJsBinaryLikeExpression::JsInstanceofExpression(instanceof) => {
instanceof.instanceof_token()
}
AnyJsBinaryLikeExpression::JsInExpression(in_expression) => in_expression.in_token(),
}
}
pub(crate) fn operator(&self) -> SyntaxResult<BinaryLikeOperator> {
match self {
AnyJsBinaryLikeExpression::JsLogicalExpression(logical) => {
logical.operator().map(BinaryLikeOperator::Logical)
}
AnyJsBinaryLikeExpression::JsBinaryExpression(binary) => {
binary.operator().map(BinaryLikeOperator::Binary)
}
AnyJsBinaryLikeExpression::JsInstanceofExpression(_) => {
Ok(BinaryLikeOperator::Instanceof)
}
AnyJsBinaryLikeExpression::JsInExpression(_) => Ok(BinaryLikeOperator::In),
}
}
/// Returns the right hand side of the binary like expression.
pub(crate) fn right(&self) -> SyntaxResult<AnyJsExpression> {
match self {
AnyJsBinaryLikeExpression::JsLogicalExpression(logical) => logical.right(),
AnyJsBinaryLikeExpression::JsBinaryExpression(binary) => binary.right(),
AnyJsBinaryLikeExpression::JsInstanceofExpression(instanceof) => instanceof.right(),
AnyJsBinaryLikeExpression::JsInExpression(in_expression) => in_expression.object(),
}
}
/// Returns `true` if the expression is inside of a test condition of `parent`.
///
/// # Examples
///
/// ```javascript
/// if (a + b) {} // true
/// if (true) { a + b } // false
/// switch (a + b) {} // true
/// ```
fn is_inside_condition(&self, parent: Option<&JsSyntaxNode>) -> bool {
parent.map_or(false, |parent| {
let test = match parent.kind() {
JsSyntaxKind::JS_IF_STATEMENT => JsIfStatement::unwrap_cast(parent.clone()).test(),
JsSyntaxKind::JS_DO_WHILE_STATEMENT => {
JsDoWhileStatement::unwrap_cast(parent.clone()).test()
}
JsSyntaxKind::JS_WHILE_STATEMENT => {
JsWhileStatement::unwrap_cast(parent.clone()).test()
}
JsSyntaxKind::JS_SWITCH_STATEMENT => {
JsSwitchStatement::unwrap_cast(parent.clone()).discriminant()
}
_ => return false,
};
test.map_or(false, |test| test.syntax() == self.syntax())
})
}
/// Determines if a binary like expression should be flattened or not. As a rule of thumb, an expression
/// can be flattened if its left hand side has the same operator-precedence
fn can_flatten(&self) -> SyntaxResult<bool> {
let left = self.left()?.into_expression();
let left_expression = left.map(|expression| expression.into_syntax());
if let Some(left_binary_like) = left_expression.and_then(AnyJsBinaryLikeExpression::cast) {
let operator = self.operator()?;
let left_operator = left_binary_like.operator()?;
Ok(should_flatten(operator, left_operator))
} else {
Ok(false)
}
}
pub(crate) fn should_inline_logical_expression(&self) -> bool {
match self {
AnyJsBinaryLikeExpression::JsLogicalExpression(logical) => {
logical.right().map_or(false, |right| match right {
AnyJsExpression::JsObjectExpression(object) => !object.members().is_empty(),
AnyJsExpression::JsArrayExpression(array) => !array.elements().is_empty(),
AnyJsExpression::JsxTagExpression(_) => true,
_ => false,
})
}
_ => false,
}
}
/// This function checks whether the chain of logical/binary expressions **should not** be indented
///
/// There are some cases where the indentation is done by the parent, so if the parent is already doing
/// the indentation, then there's no need to do a second indentation.
/// [Prettier applies]: https://github.com/prettier/prettier/blob/b0201e01ef99db799eb3716f15b7dfedb0a2e62b/src/language-js/print/binaryish.js#L122-L125
fn should_not_indent_if_parent_indents(
self: &AnyJsBinaryLikeExpression,
parent: Option<&JsSyntaxNode>,
) -> bool {
parent.map_or(false, |parent| match parent.kind() {
JsSyntaxKind::JS_RETURN_STATEMENT | JsSyntaxKind::JS_THROW_STATEMENT => true,
JsSyntaxKind::JSX_EXPRESSION_ATTRIBUTE_VALUE => true,
JsSyntaxKind::JS_TEMPLATE_ELEMENT => true,
JsSyntaxKind::JS_FOR_STATEMENT => true,
JsSyntaxKind::JS_ARROW_FUNCTION_EXPRESSION => {
is_arrow_function_body(self.syntax(), parent)
}
JsSyntaxKind::JS_CONDITIONAL_EXPRESSION => {
let grand_parent = parent.parent();
grand_parent.map_or(false, |grand_parent| {
!matches!(
grand_parent.kind(),
JsSyntaxKind::JS_RETURN_STATEMENT
| JsSyntaxKind::JS_THROW_STATEMENT
| JsSyntaxKind::JS_CALL_EXPRESSION
| JsSyntaxKind::JS_IMPORT_CALL_EXPRESSION
| JsSyntaxKind::META
)
})
}
_ => false,
})
}
}
impl From<AnyJsBinaryLikeExpression> for AnyJsExpression {
fn from(binary: AnyJsBinaryLikeExpression) -> Self {
match binary {
AnyJsBinaryLikeExpression::JsLogicalExpression(expression) => expression.into(),
AnyJsBinaryLikeExpression::JsBinaryExpression(expression) => expression.into(),
AnyJsBinaryLikeExpression::JsInstanceofExpression(expression) => expression.into(),
AnyJsBinaryLikeExpression::JsInExpression(expression) => expression.into(),
}
}
}
impl NeedsParentheses for AnyJsBinaryLikeExpression {
fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool {
match self {
AnyJsBinaryLikeExpression::JsLogicalExpression(expression) => {
expression.needs_parentheses_with_parent(parent)
}
AnyJsBinaryLikeExpression::JsBinaryExpression(expression) => {
expression.needs_parentheses_with_parent(parent)
}
AnyJsBinaryLikeExpression::JsInstanceofExpression(expression) => {
expression.needs_parentheses_with_parent(parent)
}
AnyJsBinaryLikeExpression::JsInExpression(expression) => {
expression.needs_parentheses_with_parent(parent)
}
}
}
}
/// Implements the rules when a node needs parentheses that are common across all [AnyJsBinaryLikeExpression] nodes.
pub(crate) fn needs_binary_like_parentheses(
node: &AnyJsBinaryLikeExpression,
parent: &JsSyntaxNode,
) -> bool {
match parent.kind() {
JsSyntaxKind::JS_EXTENDS_CLAUSE
| JsSyntaxKind::TS_AS_EXPRESSION
| JsSyntaxKind::TS_SATISFIES_EXPRESSION
| JsSyntaxKind::TS_TYPE_ASSERTION_EXPRESSION
| JsSyntaxKind::JS_UNARY_EXPRESSION
| JsSyntaxKind::JS_AWAIT_EXPRESSION
| JsSyntaxKind::TS_NON_NULL_ASSERTION_EXPRESSION => true,
kind if AnyJsBinaryLikeExpression::can_cast(kind) => {
let parent = AnyJsBinaryLikeExpression::unwrap_cast(parent.clone());
let operator = node.operator();
let parent_operator = parent.operator();
match (operator, parent_operator) {
(Ok(operator), Ok(parent_operator)) => {
let precedence = operator.precedence();
let parent_precedence = parent_operator.precedence();
#[allow(clippy::if_same_then_else, clippy::needless_bool)]
// If the parent has a higher precedence than parentheses are necessary to not change the semantic meaning
// when re-parsing.
if parent_precedence > precedence {
return true;
}
let is_right =
parent.right().map(AstNode::into_syntax).as_ref() == Ok(node.syntax());
// `a ** b ** c`
if is_right && parent_precedence == precedence {
return true;
}
// Add parentheses around bitwise and bit shift operators
// `a * 3 >> 5` -> `(a * 3) >> 5`
if parent_precedence.is_bitwise() || parent_precedence.is_shift() {
return true;
}
// `a % 4 + 4` -> `(a % 4) + 4)`
if parent_precedence < precedence && operator.is_remainder() {
return parent_precedence.is_additive();
}
if parent_precedence == precedence && !should_flatten(parent_operator, operator)
{
return true;
}
false
}
// Just to be sure
_ => true,
}
}
_ => {
is_callee(node.syntax(), parent)
|| is_tag(node.syntax(), parent)
|| is_spread(node.syntax(), parent)
|| is_member_object(node.syntax(), parent)
}
}
}
declare_node_union! {
/// Union type for any valid left hand side of a [AnyJsBinaryLikeExpression].
pub(crate) AnyJsBinaryLikeLeftExpression = AnyJsExpression | JsPrivateName
}
impl AnyJsBinaryLikeLeftExpression {
fn into_expression(self) -> Option<AnyJsExpression> {
match self {
AnyJsBinaryLikeLeftExpression::AnyJsExpression(expression) => Some(expression),
AnyJsBinaryLikeLeftExpression::JsPrivateName(_) => None,
}
}
}
impl NeedsParentheses for AnyJsBinaryLikeLeftExpression {
fn needs_parentheses(&self) -> bool {
match self {
AnyJsBinaryLikeLeftExpression::AnyJsExpression(expression) => {
expression.needs_parentheses()
}
AnyJsBinaryLikeLeftExpression::JsPrivateName(_) => false,
}
}
fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool {
match self {
AnyJsBinaryLikeLeftExpression::AnyJsExpression(expression) => {
expression.needs_parentheses_with_parent(parent)
}
AnyJsBinaryLikeLeftExpression::JsPrivateName(_) => false,
}
}
}
impl Format<JsFormatContext> for AnyJsBinaryLikeLeftExpression {
fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> {
match self {
AnyJsBinaryLikeLeftExpression::AnyJsExpression(expression) => {
write![f, [expression.format()]]
}
AnyJsBinaryLikeLeftExpression::JsPrivateName(private_name) => {
write![f, [private_name.format()]]
}
}
}
}
impl From<AnyJsInProperty> for AnyJsBinaryLikeLeftExpression {
fn from(property: AnyJsInProperty) -> Self {
match property {
AnyJsInProperty::AnyJsExpression(expression) => {
AnyJsBinaryLikeLeftExpression::AnyJsExpression(expression)
}
AnyJsInProperty::JsPrivateName(private_name) => {
AnyJsBinaryLikeLeftExpression::JsPrivateName(private_name)
}
}
}
}
/// Union over all binary like operators.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub(crate) enum BinaryLikeOperator {
Logical(JsLogicalOperator),
Binary(JsBinaryOperator),
Instanceof,
In,
}
impl BinaryLikeOperator {
pub const fn precedence(&self) -> OperatorPrecedence {
match self {
BinaryLikeOperator::Logical(logical) => logical.precedence(),
BinaryLikeOperator::Binary(binary) => binary.precedence(),
BinaryLikeOperator::Instanceof | BinaryLikeOperator::In => {
OperatorPrecedence::Relational
}
}
}
pub const fn is_remainder(&self) -> bool {
matches!(
self,
BinaryLikeOperator::Binary(JsBinaryOperator::Remainder)
)
}
}
impl From<JsLogicalOperator> for BinaryLikeOperator {
fn from(operator: JsLogicalOperator) -> Self {
BinaryLikeOperator::Logical(operator)
}
}
impl From<JsBinaryOperator> for BinaryLikeOperator {
fn from(binary: JsBinaryOperator) -> Self {
BinaryLikeOperator::Binary(binary)
}
}
fn is_same_binary_expression_kind(
binary: &AnyJsBinaryLikeExpression,
other: &JsSyntaxNode,
) -> bool {
match binary {
AnyJsBinaryLikeExpression::JsLogicalExpression(_) => {
matches!(other.kind(), JsSyntaxKind::JS_LOGICAL_EXPRESSION)
}
AnyJsBinaryLikeExpression::JsBinaryExpression(_)
| AnyJsBinaryLikeExpression::JsInstanceofExpression(_)
| AnyJsBinaryLikeExpression::JsInExpression(_) => {
matches!(
other.kind(),
JsSyntaxKind::JS_BINARY_EXPRESSION
| JsSyntaxKind::JS_INSTANCEOF_EXPRESSION
| JsSyntaxKind::JS_IN_EXPRESSION
)
}
}
}
/// The [BinaryLikePreorder] visits every node twice. First on the way down to find the left most binary
/// like expression, then on the way back up. This enum encodes the information whatever the
/// iterator is on its way down (`Enter`) or traversing upwards (`Exit`).
#[derive(Debug, Eq, PartialEq, Clone)]
enum VisitEvent {
Enter(AnyJsBinaryLikeExpression),
Exit(AnyJsBinaryLikeExpression),
}
/// Iterator that visits [AnyJsBinaryLikeExpression]s in pre-order.
/// This is similar to [JsSyntaxNode::descendants] but it only traverses into [AnyJsBinaryLikeExpression] and their left side
/// (the right side is never visited).
///
/// # Examples
///
/// ```js
/// a && b && c && d
/// ```
/// This produces a tree with the following shape:
///
/// ```txt
/// &&
/// / \
/// / \
/// && d && e
/// / \
/// / \
/// && c
/// / \
/// a b
/// ```
///
/// The iterator emits the following events:
///
/// * Enter(`a && b && c && d && e`)
/// * Enter(`a && b && c`)
/// * Enter(`a && b`)
/// * Exit(`a && b`)
/// * Exit(`a && b && c`)
/// * Exit(`a && b && c && d && e`)
///
/// Notice how the iterator doesn't yield events for the terminal identifiers `a`, `b`, `c`, `d`, and `e`,
/// nor for the right hand side expression `d && e`. This is because the visitor only traverses into
/// [AnyJsBinaryLikeExpression]s and of those, only along the left side.
struct BinaryLikePreorder {
/// The next node to visit or [None] if the iterator passed the start node (is at its end).
next: Option<VisitEvent>,
/// The start node. Necessary to know when to stop iterating.
start: JsSyntaxNode,
skip_subtree: bool,
}
impl BinaryLikePreorder {
fn new(start: AnyJsBinaryLikeExpression) -> Self {
Self {
start: start.syntax().clone(),
next: Some(VisitEvent::Enter(start)),
skip_subtree: false,
}
}
fn skip_subtree(&mut self) {
self.next = self.next.take().and_then(|next| match next {
VisitEvent::Enter(binary) => {
if binary.syntax() == &self.start {
None
} else {
// SAFETY: Calling `unwrap` here is safe because the iterator only enters (traverses into) a node
// if it is a valid binary like expression and it is guaranteed to have a parent.
let expression = binary
.syntax()
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | true |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/utils/quickcheck_utils.rs | crates/rome_js_formatter/src/utils/quickcheck_utils.rs | /// Generates a string with only ascii chars
#[derive(Debug, Clone)]
pub struct AsciiString(String);
impl std::ops::Deref for AsciiString {
type Target = str;
fn deref(&self) -> &Self::Target {
self.0.as_str()
}
}
impl<'a> PartialEq<AsciiString> for &'a str {
fn eq(&self, other: &AsciiString) -> bool {
self == &other.0.as_str()
}
}
impl std::fmt::Display for AsciiString {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl quickcheck::Arbitrary for AsciiString {
fn arbitrary(g: &mut quickcheck::Gen) -> Self {
let s = String::arbitrary(g);
let mut ascii = String::new();
for chr in s.chars() {
if chr.is_ascii() {
ascii.push(chr);
} else {
const WIDTH: u8 = b'~' - b' ';
let chr = b' ' + (u8::arbitrary(g) % WIDTH);
ascii.push(chr as char);
}
}
assert!(ascii.is_ascii());
Self(ascii)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/utils/string_utils.rs | crates/rome_js_formatter/src/utils/string_utils.rs | use crate::context::{JsFormatOptions, QuoteProperties, QuoteStyle};
use crate::prelude::*;
use rome_formatter::token::string::normalize_string;
use rome_js_syntax::JsSyntaxKind::{JSX_STRING_LITERAL, JS_STRING_LITERAL};
use rome_js_syntax::{JsFileSource, JsSyntaxToken};
use std::borrow::Cow;
use unicode_width::UnicodeWidthStr;
#[derive(Eq, PartialEq, Debug)]
pub(crate) enum StringLiteralParentKind {
/// Variant to track tokens that are inside an expression
Expression,
/// Variant to track tokens that are inside a member
Member,
/// Variant used when the string literal is inside a directive. This will apply
/// a simplified logic of normalisation
Directive,
}
/// Data structure of convenience to format string literals
pub(crate) struct FormatLiteralStringToken<'token> {
/// The current token
token: &'token JsSyntaxToken,
/// The parent that holds the token
parent_kind: StringLiteralParentKind,
}
impl<'token> FormatLiteralStringToken<'token> {
pub fn new(token: &'token JsSyntaxToken, parent_kind: StringLiteralParentKind) -> Self {
Self { token, parent_kind }
}
fn token(&self) -> &'token JsSyntaxToken {
self.token
}
pub fn clean_text(&self, options: &JsFormatOptions) -> CleanedStringLiteralText {
let token = self.token();
debug_assert!(
matches!(token.kind(), JS_STRING_LITERAL | JSX_STRING_LITERAL),
"Found kind {:?}",
token.kind()
);
let chosen_quote_style = match token.kind() {
JSX_STRING_LITERAL => options.jsx_quote_style(),
_ => options.quote_style(),
};
let chosen_quote_properties = options.quote_properties();
let mut string_cleaner =
LiteralStringNormaliser::new(self, chosen_quote_style, chosen_quote_properties);
let content = string_cleaner.normalise_text(options.source_type().into());
let normalized_text_width = content.width();
CleanedStringLiteralText {
text: content,
width: normalized_text_width,
token,
}
}
}
pub(crate) struct CleanedStringLiteralText<'a> {
token: &'a JsSyntaxToken,
text: Cow<'a, str>,
width: usize,
}
impl CleanedStringLiteralText<'_> {
pub fn width(&self) -> usize {
self.width
}
}
impl Format<JsFormatContext> for CleanedStringLiteralText<'_> {
fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
format_replaced(
self.token,
&syntax_token_cow_slice(
self.text.clone(),
self.token,
self.token.text_trimmed_range().start(),
),
)
.fmt(f)
}
}
impl Format<JsFormatContext> for FormatLiteralStringToken<'_> {
fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> {
let cleaned = self.clean_text(f.options());
cleaned.fmt(f)
}
}
/// Data structure of convenience to store some information about the
/// string that has been processed
struct StringInformation {
/// This is the quote that the is calculated and eventually used inside the string.
/// It could be different from the one inside the formatter options
preferred_quote: QuoteStyle,
/// It flags if the raw content has quotes (single or double). The raw content is the
/// content of a string literal without the quotes
raw_content_has_quotes: bool,
}
impl FormatLiteralStringToken<'_> {
/// This function determines which quotes should be used inside to enclose the string.
/// The function take as a input the string **without quotes**.
///
/// # How it works
///
/// The function determines the preferred quote and alternate quote.
/// The preferred quote is the one that comes from the formatter options. The alternate quote is the other one.
///
/// We check how many preferred quotes we have inside the content. If this number is greater then the
/// number alternate quotes that we have inside the content,
/// then we swap them, so we can reduce the number of escaped quotes.
///
/// For example, let's suppose that the preferred quote is double, and we have a string like this:
/// ```js
/// (" content \"\"\" don't ")
/// ```
/// Excluding the quotes at the start and beginning, we have three double quote and one single quote.
/// If we decided to keep them like this, we would have three escaped quotes.
///
/// But then, we choose the single quote as preferred quote and we would have only one quote that is escaped,
/// resulting into a string like this:
/// ```js
/// (' content """ dont\'t ')
/// ```
/// Like this, we reduced the number of escaped quotes.
fn compute_string_information(&self, chosen_quote: QuoteStyle) -> StringInformation {
let literal = self.token().text_trimmed();
let alternate = chosen_quote.other();
let char_count = literal.chars().count();
let (preferred_quotes_count, alternate_quotes_count) = literal.chars().enumerate().fold(
(0, 0),
|(preferred_quotes_counter, alternate_quotes_counter), (index, current_character)| {
if index == 0 || index == char_count - 1 {
(preferred_quotes_counter, alternate_quotes_counter)
} else if current_character == chosen_quote.as_char() {
(preferred_quotes_counter + 1, alternate_quotes_counter)
} else if current_character == alternate.as_char() {
(preferred_quotes_counter, alternate_quotes_counter + 1)
} else {
(preferred_quotes_counter, alternate_quotes_counter)
}
},
);
StringInformation {
raw_content_has_quotes: preferred_quotes_count > 0 || alternate_quotes_count > 0,
preferred_quote: if preferred_quotes_count > alternate_quotes_count {
alternate
} else {
chosen_quote
},
}
}
}
/// Struct of convenience used to manipulate the string. It saves some state in order to apply
/// the normalise process.
struct LiteralStringNormaliser<'token> {
/// The current token
token: &'token FormatLiteralStringToken<'token>,
/// The quote that was set inside the configuration
chosen_quote_style: QuoteStyle,
/// When properties in objects are quoted that was set inside the configuration
chosen_quote_properties: QuoteProperties,
}
/// Convenience enum to map [rome_js_syntax::JsFileSource] by just reading
/// the type of file
#[derive(Eq, PartialEq)]
pub(crate) enum SourceFileKind {
TypeScript,
JavaScript,
}
impl From<JsFileSource> for SourceFileKind {
fn from(st: JsFileSource) -> Self {
if st.language().is_typescript() {
Self::TypeScript
} else {
Self::JavaScript
}
}
}
impl<'token> LiteralStringNormaliser<'token> {
pub fn new(
token: &'token FormatLiteralStringToken<'_>,
chosen_quote_style: QuoteStyle,
chosen_quote_properties: QuoteProperties,
) -> Self {
Self {
token,
chosen_quote_style,
chosen_quote_properties,
}
}
fn normalise_text(&mut self, file_source: SourceFileKind) -> Cow<'token, str> {
let string_information = self
.token
.compute_string_information(self.chosen_quote_style);
match self.token.parent_kind {
StringLiteralParentKind::Expression => {
self.normalise_string_literal(string_information)
}
StringLiteralParentKind::Directive => self.normalise_directive(&string_information),
StringLiteralParentKind::Member => {
self.normalise_type_member(string_information, file_source)
}
}
}
fn get_token(&self) -> &'token JsSyntaxToken {
self.token.token()
}
fn normalise_directive(&mut self, string_information: &StringInformation) -> Cow<'token, str> {
let content = self.normalize_string(string_information);
match content {
Cow::Borrowed(content) => self.swap_quotes(content, string_information),
Cow::Owned(content) => Cow::Owned(
self.swap_quotes(content.as_ref(), string_information)
.into_owned(),
),
}
}
/// We can change the text only if there are alphanumeric or alphabetic characters, depending on the file source
fn can_remove_quotes(&self, file_source: SourceFileKind) -> bool {
if self.chosen_quote_properties == QuoteProperties::Preserve {
return false;
}
let text_to_check = self.raw_content();
// Text here is quoteless. If it's empty, it means it is an empty string and we can't
// do any transformation
if text_to_check.is_empty() {
return false;
}
let mut has_seen_number = false;
text_to_check.chars().enumerate().all(|(index, c)| {
if index == 0 && c.is_ascii_digit() {
// We can't remove quotes if the member is octal literals.
if c == '0' && text_to_check.len() > 1 {
return false;
}
// In TypeScript, numbers like members have different meaning from numbers.
// Hence, if we see a number, we bail straightaway
if file_source == SourceFileKind::TypeScript {
return false;
} else {
has_seen_number = true;
}
}
let is_eligible_character = if has_seen_number {
// as we've seen a number, now eligible characters can only contain numbers
c.is_ascii_digit()
} else {
c.is_alphabetic() || c.is_ascii_digit()
};
is_eligible_character || matches!(c, '_' | '$')
})
}
fn normalise_type_member(
&mut self,
string_information: StringInformation,
file_source: SourceFileKind,
) -> Cow<'token, str> {
if self.can_remove_quotes(file_source) {
return Cow::Owned(self.raw_content().to_string());
}
self.normalise_string_literal(string_information)
}
fn normalise_string_literal(&self, string_information: StringInformation) -> Cow<'token, str> {
let preferred_quote = string_information.preferred_quote;
let polished_raw_content = self.normalize_string(&string_information);
match polished_raw_content {
Cow::Borrowed(raw_content) => {
let final_content = self.swap_quotes(raw_content, &string_information);
match final_content {
Cow::Borrowed(final_content) => Cow::Borrowed(final_content),
Cow::Owned(final_content) => Cow::Owned(final_content),
}
}
Cow::Owned(s) => {
// content is owned, meaning we allocated a new string,
// so we force replacing quotes, regardless
let final_content = std::format!(
"{}{}{}",
preferred_quote.as_char(),
s.as_str(),
preferred_quote.as_char()
);
Cow::Owned(final_content)
}
}
}
fn normalize_string(&self, string_information: &StringInformation) -> Cow<'token, str> {
let raw_content = self.raw_content();
if matches!(self.token.parent_kind, StringLiteralParentKind::Directive) {
return Cow::Borrowed(raw_content);
}
normalize_string(raw_content, string_information.preferred_quote.into())
}
fn raw_content(&self) -> &'token str {
let content = self.get_token().text_trimmed();
&content[1..content.len() - 1]
}
fn swap_quotes<S: Into<&'token str>>(
&self,
content_to_use: S,
string_information: &StringInformation,
) -> Cow<'token, str> {
let original_content = self.get_token().text_trimmed();
let preferred_quote = string_information.preferred_quote;
let other_quote = preferred_quote.other().as_char();
let raw_content_has_quotes = string_information.raw_content_has_quotes;
if raw_content_has_quotes {
Cow::Borrowed(original_content)
} else if original_content.starts_with(other_quote) {
Cow::Owned(std::format!(
"{}{}{}",
preferred_quote.as_char(),
content_to_use.into(),
preferred_quote.as_char()
))
} else {
Cow::Borrowed(original_content)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::context::QuoteStyle;
use crate::utils::quickcheck_utils::*;
use crate::utils::FormatLiteralStringToken;
use quickcheck_macros::*;
use rome_formatter::token::string::ToAsciiLowercaseCow;
use rome_js_factory::JsSyntaxTreeBuilder;
use rome_js_syntax::JsSyntaxKind::{JS_STRING_LITERAL, JS_STRING_LITERAL_EXPRESSION};
use rome_js_syntax::{JsStringLiteralExpression, JsSyntaxToken};
use rome_rowan::AstNode;
use std::borrow::Cow;
#[quickcheck]
fn to_ascii_lowercase_cow_always_returns_same_value_as_string_to_lowercase(txt: AsciiString) {
assert_eq!(
txt.to_lowercase(),
txt.to_ascii_lowercase_cow().into_owned()
);
}
#[quickcheck]
fn to_ascii_lowercase_cow_returns_borrowed_when_all_chars_are_lowercase(txt: AsciiString) {
let txt = txt.to_lowercase();
assert!(matches!(txt.to_ascii_lowercase_cow(), Cow::Borrowed(s) if s == txt));
}
#[quickcheck]
fn to_ascii_lowercase_cow_returns_owned_when_some_chars_are_not_lowercase(txt: AsciiString) {
let txt = std::format!("{}A", txt); //guarantees at least one uppercase letter
assert!(matches!(txt.to_ascii_lowercase_cow(), Cow::Owned(s) if s == txt.to_lowercase()));
}
fn generate_syntax_token(input: &str) -> JsSyntaxToken {
let mut tree_builder = JsSyntaxTreeBuilder::new();
tree_builder.start_node(JS_STRING_LITERAL_EXPRESSION);
tree_builder.token(JS_STRING_LITERAL, input);
tree_builder.finish_node();
let root = tree_builder.finish();
JsStringLiteralExpression::cast(root)
.unwrap()
.value_token()
.unwrap()
}
enum AsToken {
Directive,
String,
Member,
}
impl AsToken {
fn into_token(self, token: &JsSyntaxToken) -> FormatLiteralStringToken {
match self {
AsToken::Directive => {
FormatLiteralStringToken::new(token, StringLiteralParentKind::Directive)
}
AsToken::String => {
FormatLiteralStringToken::new(token, StringLiteralParentKind::Expression)
}
AsToken::Member => {
FormatLiteralStringToken::new(token, StringLiteralParentKind::Member)
}
}
}
}
fn assert_borrowed_token(
input: &str,
quote: QuoteStyle,
quote_properties: QuoteProperties,
as_token: AsToken,
source: SourceFileKind,
) {
let token = generate_syntax_token(input);
let string_token = as_token.into_token(&token);
let mut string_cleaner =
LiteralStringNormaliser::new(&string_token, quote, quote_properties);
let content = string_cleaner.normalise_text(source);
assert_eq!(content, Cow::Borrowed(input))
}
fn assert_owned_token(
input: &str,
output: &str,
quote: QuoteStyle,
quote_properties: QuoteProperties,
as_token: AsToken,
source: SourceFileKind,
) {
let token = generate_syntax_token(input);
let string_token = as_token.into_token(&token);
let mut string_cleaner =
LiteralStringNormaliser::new(&string_token, quote, quote_properties);
let content = string_cleaner.normalise_text(source);
let owned: Cow<str> = Cow::Owned(output.to_string());
assert_eq!(content, owned)
}
#[test]
fn string_borrowed() {
let quote = QuoteStyle::Double;
let quote_properties = QuoteProperties::AsNeeded;
let inputs = [r#""content""#, r#""content with single ' quote ""#];
for input in inputs {
assert_borrowed_token(
input,
quote,
quote_properties,
AsToken::String,
SourceFileKind::JavaScript,
)
}
}
#[test]
fn string_owned() {
let quote = QuoteStyle::Double;
let quote_properties = QuoteProperties::AsNeeded;
let inputs = [
(r#"" content '' \"\"\" ""#, r#"' content \'\' """ '"#),
(r#"" content \"\"\"\" '' ""#, r#"' content """" \'\' '"#),
(r#"" content ''''' \" ""#, r#"" content ''''' \" ""#),
(r#"" content \'\' \" ""#, r#"" content '' \" ""#),
(r#"" content \\' \" ""#, r#"" content \\' \" ""#),
];
for (input, output) in inputs {
assert_owned_token(
input,
output,
quote,
quote_properties,
AsToken::String,
SourceFileKind::JavaScript,
)
}
}
#[test]
fn directive_borrowed() {
let quote = QuoteStyle::Double;
let quote_properties = QuoteProperties::AsNeeded;
let inputs = [r#""use strict '""#];
for input in inputs {
assert_borrowed_token(
input,
quote,
quote_properties,
AsToken::Directive,
SourceFileKind::JavaScript,
)
}
}
#[test]
fn directive_owned() {
let quote = QuoteStyle::Double;
let quote_properties = QuoteProperties::AsNeeded;
let inputs = [(r#"' use strict '"#, r#"" use strict ""#)];
for (input, output) in inputs {
assert_owned_token(
input,
output,
quote,
quote_properties,
AsToken::Directive,
SourceFileKind::JavaScript,
)
}
}
#[test]
fn member_borrowed() {
let quote = QuoteStyle::Double;
let quote_properties = QuoteProperties::AsNeeded;
let inputs = [r#""cant @ be moved""#, r#""1674""#, r#""33n""#];
for input in inputs {
assert_borrowed_token(
input,
quote,
quote_properties,
AsToken::Member,
SourceFileKind::TypeScript,
)
}
}
#[test]
fn member_owned() {
let quote = QuoteStyle::Double;
let quote_properties = QuoteProperties::AsNeeded;
let inputs = [(r#""string""#, r#"string"#)];
for (input, output) in inputs {
assert_owned_token(
input,
output,
quote,
quote_properties,
AsToken::Member,
SourceFileKind::TypeScript,
)
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/utils/member_chain/chain_member.rs | crates/rome_js_formatter/src/utils/member_chain/chain_member.rs | use crate::js::expressions::computed_member_expression::FormatComputedMemberLookup;
use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::{
JsCallExpression, JsCallExpressionFields, JsComputedMemberExpression, JsImportCallExpression,
JsStaticMemberExpression, JsStaticMemberExpressionFields, JsSyntaxNode,
TsNonNullAssertionExpression, TsNonNullAssertionExpressionFields,
};
use rome_rowan::AstNode;
use std::fmt::Debug;
#[derive(Copy, Clone, Debug)]
pub(crate) enum CallExpressionPosition {
/// At the start of a call chain.
/// `of` in `of().test`
Start,
/// Somewhere in the middle.
///
/// `b` in `a.b().c()`
Middle,
/// At the end of a call chain (root)
/// `c` in `a.b.c()`
End,
}
/// Data structure that holds the node with its formatted version
#[derive(Clone, Debug)]
pub(crate) enum ChainMember {
/// Holds onto a [rome_js_syntax::JsStaticMemberExpression]
StaticMember {
expression: JsStaticMemberExpression,
},
/// Holds onto a [rome_js_syntax::JsCallExpression]
CallExpression {
expression: JsCallExpression,
position: CallExpressionPosition,
},
/// Holds onto a [rome_js_syntax::JsComputedMemberExpression]
ComputedMember {
expression: JsComputedMemberExpression,
},
TsNonNullAssertionExpression {
expression: TsNonNullAssertionExpression,
},
/// Any other node that are not [rome_js_syntax::JsCallExpression] or [rome_js_syntax::JsStaticMemberExpression]
/// Are tracked using this variant
Node(JsSyntaxNode),
}
impl ChainMember {
/// checks if the current node is a [rome_js_syntax::JsCallExpression], or a [rome_js_syntax::JsImportExpression]
pub fn is_call_like_expression(&self) -> bool {
match self {
ChainMember::CallExpression { .. } => true,
ChainMember::Node(node) => {
JsImportCallExpression::can_cast(node.kind())
| JsCallExpression::can_cast(node.kind())
}
_ => false,
}
}
pub(crate) const fn is_call_expression(&self) -> bool {
matches!(self, ChainMember::CallExpression { .. })
}
pub(crate) fn syntax(&self) -> &JsSyntaxNode {
match self {
ChainMember::StaticMember { expression, .. } => expression.syntax(),
ChainMember::CallExpression { expression, .. } => expression.syntax(),
ChainMember::ComputedMember { expression, .. } => expression.syntax(),
ChainMember::TsNonNullAssertionExpression { expression } => expression.syntax(),
ChainMember::Node(node) => node,
}
}
pub const fn is_computed_expression(&self) -> bool {
matches!(self, ChainMember::ComputedMember { .. })
}
pub(super) fn needs_empty_line_before(&self) -> bool {
match self {
ChainMember::StaticMember { expression } => {
let operator = expression.operator_token();
match operator {
Ok(operator) => get_lines_before_token(&operator) > 1,
_ => false,
}
}
ChainMember::ComputedMember { expression } => {
let l_brack_token = expression.l_brack_token();
match l_brack_token {
Ok(l_brack_token) => {
get_lines_before_token(
&expression.optional_chain_token().unwrap_or(l_brack_token),
) > 1
}
_ => false,
}
}
_ => false,
}
}
}
impl Format<JsFormatContext> for ChainMember {
fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> {
if self.needs_empty_line_before() {
write!(f, [empty_line()])?;
}
match self {
ChainMember::StaticMember { expression } => {
let JsStaticMemberExpressionFields {
// Formatted as part of the previous item
object: _,
operator_token,
member,
} = expression.as_fields();
write!(
f,
[
format_leading_comments(expression.syntax()),
operator_token.format(),
member.format(),
format_trailing_comments(expression.syntax())
]
)
}
ChainMember::TsNonNullAssertionExpression { expression } => {
let TsNonNullAssertionExpressionFields {
expression: _,
excl_token,
} = expression.as_fields();
write!(
f,
[
format_leading_comments(expression.syntax()),
excl_token.format(),
format_trailing_comments(expression.syntax())
]
)
}
ChainMember::CallExpression {
expression,
position,
} => {
let JsCallExpressionFields {
// Formatted as part of the previous item
callee: _,
optional_chain_token,
type_arguments,
arguments,
} = expression.as_fields();
match position {
CallExpressionPosition::Start => write!(f, [expression.format()]),
CallExpressionPosition::Middle => {
write!(
f,
[
format_leading_comments(expression.syntax()),
optional_chain_token.format(),
type_arguments.format(),
arguments.format(),
format_trailing_comments(expression.syntax())
]
)
}
CallExpressionPosition::End => {
write!(
f,
[
optional_chain_token.format(),
type_arguments.format(),
arguments.format(),
]
)
}
}
}
ChainMember::ComputedMember { expression } => {
write!(
f,
[
format_leading_comments(expression.syntax()),
FormatComputedMemberLookup::new(&expression.clone().into()),
format_trailing_comments(expression.syntax())
]
)
}
ChainMember::Node(node) => {
write!(f, [node.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/utils/member_chain/mod.rs | crates/rome_js_formatter/src/utils/member_chain/mod.rs | //! Utility function that applies some heuristic to format chain member expressions and call expressions
//!
//! We want to transform code that looks like this:
//!
//! ```js
//! something.execute().then().then().catch()
//! ```
//!
//! To something like this:
//!
//! ```js
//! something
//! .execute()
//! .then()
//! .then()
//! .catch()
//! ```
//!
//! In order to achieve that we use the same heuristic that [Prettier applies](https://github.com/prettier/prettier/blob/main/src/language-js/print/member-chain.js).
//!
//! The process is the following:
//!
//! ### Flattening the AST
//! We flatten the AST. See, the code above is actually nested, where the first member expression (`something`)
//! that we see is actually the last one. This is a oversimplified version of the AST:
//!
//! ```block
//! [
//! .catch() [
//! .then() [
//! .then() [
//! .execute() [
//! something
//! ]
//! ]
//! ]
//! ]
//! ]
//! ```
//! So we need to navigate the AST and make sure that `something` is actually
//! the first one. In a sense, we have to revert the chain of children. We will do that using a recursion.
//!
//! While we navigate the AST and we found particular nodes that we want to track, we also
//! format them. The format of these nodes is different from the standard version.
//!
//! Our formatter makes sure that we don't format twice the same nodes. Let's say for example that
//! we find a `something().execute()`, its AST is like this:
//!
//! ```block
//! JsCallExpression {
//! callee: JsStaticMember {
//! object: JsCallExpression {
//! callee: Reference {
//! execute
//! }
//! }
//! }
//! }
//! ```
//!
//! When we track the first [rome_js_syntax::JsCallExpression], we hold basically all the children,
//! that applies for the rest of the nodes. If we decided to format all the children of each node,
//! we will risk to format the last node, the `Reference`, four times.
//!
//! To avoid this, when we encounter particular nodes, we don't format all of its children, but defer
//! the formatting to the child itself.
//!
//! The end result of the flattening, will create an array of something like this:
//!
//! ```block
//! [ Identifier, JsCallExpression, JsStaticMember, JsCallExpression ]
//! ```
//!
//! ### Grouping
//!
//! After the flattening, we start the grouping. We want to group nodes in a way that will help us
//! to apply a deterministic formatting.
//! - first group will be the identifier
//! - the rest of the groups will be will start StaticMemberExpression followed by the rest of the nodes,
//! right before the end of the next StaticMemberExpression
//!
//! The first group is special, because it holds the reference; it has its own heuristic.
//! Inside the first group we store the first element of the flattened array, then:
//!
//! 1. as many as [rome_js_syntax::JsCallExpression] we can find, this cover cases like
//! `something()()().then()`;
//! 2. as many as [rome_js_syntax::JsComputedMemberExpression] we can find, this cover cases like
//! `something()()[1][3].then()`;
//! 3. as many as consecutive [rome_js_syntax::JsStaticMemberExpression] or [rome_js_syntax::JsComputedMemberExpression], this cover cases like
//! `this.items[0].then()`
//!
//! The rest of the groups are essentially a sequence of `[StaticMemberExpression , CallExpression]`.
//! In order to achieve that, we simply start looping through the rest of the flatten items that we haven't seen.
//!
//! Eventually, we should have something like this:
//!
//! ```block
//! [
//! [ReferenceIdentifier, CallExpression], // with possible computed expressions in the middle
//! [StaticMemberExpression, StaticMemberExpression, CallExpression],
//! [StaticMemberExpression, CallExpression],
//! [StaticMemberExpression],
//! ]
//! ```
mod chain_member;
mod groups;
mod simple_argument;
use crate::context::TabWidth;
use crate::prelude::*;
use crate::utils::is_long_curried_call;
use crate::utils::member_chain::chain_member::{CallExpressionPosition, ChainMember};
use crate::utils::member_chain::groups::{
MemberChainGroup, MemberChainGroupsBuilder, TailChainGroups,
};
use crate::utils::member_chain::simple_argument::SimpleArgument;
use crate::JsLabels;
use rome_formatter::{write, Buffer};
use rome_js_syntax::{
AnyJsCallArgument, AnyJsExpression, AnyJsLiteralExpression, JsCallExpression,
JsIdentifierExpression, JsSyntaxKind, JsSyntaxNode, JsSyntaxToken, JsThisExpression,
};
use rome_rowan::{AstNode, SyntaxResult};
use std::iter::FusedIterator;
#[derive(Debug, Clone)]
pub(crate) struct MemberChain {
root: JsCallExpression,
head: MemberChainGroup,
tail: TailChainGroups,
}
impl MemberChain {
pub(crate) fn from_call_expression(
call_expression: JsCallExpression,
comments: &JsComments,
tab_width: TabWidth,
) -> SyntaxResult<MemberChain> {
let parent = call_expression.syntax().parent();
let mut chain_members =
ChainMembersIterator::new(call_expression.clone().into(), comments).collect::<Vec<_>>();
chain_members.reverse();
// as explained before, the first group is particular, so we calculate it
let (head_group, remaining_members) =
split_members_into_head_and_remaining_groups(chain_members);
// `flattened_items` now contains only the nodes that should have a sequence of
// `[ StaticMemberExpression -> AnyNode + JsCallExpression ]`
let tail_groups = compute_remaining_groups(remaining_members, comments);
let mut member_chain = MemberChain {
head: head_group,
tail: tail_groups,
root: call_expression,
};
// Here we check if the first element of Groups::groups can be moved inside the head.
// If so, then we extract it and concatenate it together with the head.
member_chain.maybe_merge_with_first_group(comments, tab_width, parent.as_ref());
Ok(member_chain)
}
/// Here we check if the first group can be merged to the head. If so, then
/// we move out the first group out of the groups
fn maybe_merge_with_first_group(
&mut self,
comments: &JsComments,
tab_width: TabWidth,
parent: Option<&JsSyntaxNode>,
) {
if self.should_merge_tail_with_head(parent, tab_width, comments) {
let group = self.tail.pop_first().unwrap();
self.head.extend_members(group.into_members());
}
}
/// This function checks if the current grouping should be merged with the first group.
fn should_merge_tail_with_head(
&self,
parent: Option<&JsSyntaxNode>,
tab_width: TabWidth,
comments: &JsComments,
) -> bool {
let first_group = match self.tail.first() {
None => {
return false;
}
Some(first_group) => first_group,
};
let has_comments = first_group
.members()
.first()
.map_or(false, |member| comments.has_comments(member.syntax()));
if has_comments {
return false;
}
let has_computed_property = first_group
.members()
.first()
.map_or(false, |item| item.is_computed_expression());
if self.head.members().len() == 1 {
let only_member = &self.head.members()[0];
let in_expression_statement = parent.map_or(false, |parent| {
parent.kind() == JsSyntaxKind::JS_EXPRESSION_STATEMENT
});
match only_member {
ChainMember::Node(node) => {
if JsThisExpression::can_cast(node.kind()) {
true
} else if let Some(identifier) = JsIdentifierExpression::cast_ref(node) {
let is_factory = identifier
.name()
.and_then(|name| name.value_token())
.as_ref()
.map_or(false, is_factory);
has_computed_property ||
is_factory ||
// If an identifier has a name that is shorter than the tab with, then we join it with the "head"
(in_expression_statement
&& has_short_name(&identifier, tab_width))
} else {
false
}
}
_ => false,
}
} else if let Some(ChainMember::StaticMember { expression }) = self.head.members().last() {
let member = expression.member().ok();
let is_factory = member
.as_ref()
.and_then(|member| member.as_js_name())
.and_then(|name| name.value_token().ok())
.as_ref()
.map_or(false, is_factory);
has_computed_property || is_factory
} else {
false
}
}
/// It tells if the groups should break on multiple lines
fn groups_should_break(&self, f: &mut JsFormatter) -> FormatResult<bool> {
let comments = f.comments();
let node_has_comments =
self.head.has_comments(comments) || self.tail.has_comments(comments);
if node_has_comments {
return Ok(true);
}
let mut call_expressions = self
.members()
.filter_map(|member| match member {
ChainMember::CallExpression { expression, .. } => Some(expression),
_ => None,
})
.peekable();
let mut calls_count = 0u32;
let mut any_has_function_like_argument = false;
let mut any_complex_args = false;
while let Some(call) = call_expressions.next() {
calls_count += 1;
if call_expressions.peek().is_some() {
any_has_function_like_argument =
any_has_function_like_argument || has_arrow_or_function_expression_arg(call)
}
any_complex_args = any_complex_args || !has_simple_arguments(call);
}
if calls_count > 2 && any_complex_args {
return Ok(true);
}
if self.last_call_breaks(f)? && any_has_function_like_argument {
return Ok(true);
}
if !self.tail.is_empty() && self.head.will_break(f)? {
return Ok(true);
}
if self.tail.any_except_last_will_break(f)? {
return Ok(true);
}
Ok(false)
}
/// We retrieve all the call expressions inside the group and we check if
/// their arguments are not simple.
fn last_call_breaks(&self, f: &mut JsFormatter) -> FormatResult<bool> {
let last_group = self.last_group();
if let Some(ChainMember::CallExpression { .. }) = last_group.members().last() {
last_group.will_break(f)
} else {
Ok(false)
}
}
fn last_group(&self) -> &MemberChainGroup {
self.tail.last().unwrap_or(&self.head)
}
/// Returns an iterator over all members in the member chain
fn members(&self) -> impl Iterator<Item = &ChainMember> + DoubleEndedIterator {
self.head.members().iter().chain(self.tail.members())
}
fn has_comments(&self, comments: &JsComments) -> bool {
let mut members = self.members();
if let Some(first) = members.next() {
if comments.has_trailing_comments(first.syntax()) {
return true;
}
}
// Ignore the root member because comments are printed before/after the member chain.
members.next_back();
for member in members {
if comments.has_leading_comments(member.syntax())
|| comments.has_trailing_comments(member.syntax())
{
return true;
}
}
false
}
}
impl Format<JsFormatContext> for MemberChain {
fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
let has_comments = self.has_comments(f.comments());
let format_one_line = format_with(|f| {
let mut joiner = f.join();
joiner.entry(&self.head);
joiner.entries(self.tail.iter());
joiner.finish()
});
if self.tail.len() <= 1 && !has_comments {
return if is_long_curried_call(Some(&self.root)) {
write!(f, [format_one_line])
} else {
write!(f, [group(&format_one_line)])
};
}
let has_empty_line = match self.tail.members().next() {
Some(member) => member.needs_empty_line_before(),
None => false,
};
let format_tail = format_with(|f| {
if !has_empty_line {
write!(f, [hard_line_break()])?;
}
f.join_with(hard_line_break())
.entries(self.tail.iter())
.finish()
});
let format_expanded = format_with(|f| write!(f, [self.head, indent(&group(&format_tail))]));
let format_content = format_with(|f| {
if self.groups_should_break(f)? {
write!(f, [group(&format_expanded)])
} else {
if has_empty_line || self.last_group().will_break(f)? {
write!(f, [expand_parent()])?;
}
write!(f, [best_fitting!(format_one_line, format_expanded)])
}
});
write!(
f,
[labelled(
LabelId::of(JsLabels::MemberChain),
&format_content
)]
)
}
}
/// Splits the members into two groups:
/// * The head group that contains all notes that are not a sequence of: `[ StaticMemberExpression -> AnyNode + JsCallExpression ]`
/// * The remaining members
fn split_members_into_head_and_remaining_groups(
mut members: Vec<ChainMember>,
) -> (MemberChainGroup, Vec<ChainMember>) {
// This where we apply the first two points explained in the description of the main public function.
// We want to keep iterating over the items until we have call expressions
// - `something()()()()`
// - `something[1][2][4]`
// - `something[1]()[3]()`
// - `something()[2].something.else[0]`
let non_call_or_array_member_access_start = members
.iter()
.enumerate()
// The first member is always part of the first group
.skip(1)
.find_map(|(index, member)| match member {
ChainMember::CallExpression { .. }
| ChainMember::TsNonNullAssertionExpression { .. } => None,
ChainMember::ComputedMember { expression } => {
if matches!(
expression.member(),
Ok(AnyJsExpression::AnyJsLiteralExpression(
AnyJsLiteralExpression::JsNumberLiteralExpression(_),
))
) {
None
} else {
Some(index)
}
}
_ => Some(index),
})
.unwrap_or(members.len());
let first_group_end_index = if !members
.first()
.map_or(false, |member| member.is_call_expression())
{
// Take as many member access chains as possible
let rest = &members[non_call_or_array_member_access_start..];
let member_end = rest
.iter()
.enumerate()
.find_map(|(index, member)| match member {
ChainMember::StaticMember { .. } | ChainMember::ComputedMember { .. } => {
let next_is_member = matches!(
rest.get(index + 1),
Some(ChainMember::ComputedMember { .. } | ChainMember::StaticMember { .. })
);
(!next_is_member).then_some(index)
}
_ => Some(index),
})
.unwrap_or(rest.len());
non_call_or_array_member_access_start + member_end
} else {
non_call_or_array_member_access_start
};
let remaining = members.split_off(first_group_end_index);
(MemberChainGroup::from(members), remaining)
}
/// computes groups coming after the first group
fn compute_remaining_groups(members: Vec<ChainMember>, comments: &JsComments) -> TailChainGroups {
let mut has_seen_call_expression = false;
let mut groups_builder = MemberChainGroupsBuilder::default();
for member in members {
let has_trailing_comments = comments.has_trailing_comments(member.syntax());
match member {
// [0] should be appended at the end of the group instead of the
// beginning of the next one
ChainMember::ComputedMember { .. } if is_computed_array_member_access(&member) => {
groups_builder.start_or_continue_group(member);
}
ChainMember::StaticMember { .. } | ChainMember::ComputedMember { .. } => {
// if we have seen a JsCallExpression, we want to close the group.
// The resultant group will be something like: [ . , then, () ];
// `.` and `then` belong to the previous StaticMemberExpression,
// and `()` belong to the call expression we just encountered
if has_seen_call_expression {
groups_builder.close_group();
groups_builder.start_group(member);
has_seen_call_expression = false;
} else {
groups_builder.start_or_continue_group(member);
}
}
ChainMember::CallExpression { .. } => {
groups_builder.start_or_continue_group(member);
has_seen_call_expression = true;
}
ChainMember::TsNonNullAssertionExpression { .. } => {
groups_builder.start_or_continue_group(member);
}
ChainMember::Node(_) if member.is_call_like_expression() => {
groups_builder.start_or_continue_group(member);
has_seen_call_expression = true;
}
ChainMember::Node(_) => groups_builder.continue_group(member),
}
// Close the group immediately if the node had any trailing comments to
// ensure those are printed in a trailing position for the token they
// were originally commenting
if has_trailing_comments {
groups_builder.close_group();
has_seen_call_expression = false;
}
}
groups_builder.finish()
}
fn is_computed_array_member_access(member: &ChainMember) -> bool {
if let ChainMember::ComputedMember { expression } = member {
matches!(
expression.member(),
Ok(AnyJsExpression::AnyJsLiteralExpression(
AnyJsLiteralExpression::JsNumberLiteralExpression(_)
))
)
} else {
false
}
}
fn has_arrow_or_function_expression_arg(call: &JsCallExpression) -> bool {
call.arguments().map_or(false, |arguments| {
arguments.args().iter().any(|argument| {
matches!(
argument,
Ok(AnyJsCallArgument::AnyJsExpression(
AnyJsExpression::JsArrowFunctionExpression(_)
| AnyJsExpression::JsFunctionExpression(_)
))
)
})
})
}
fn has_simple_arguments(call: &JsCallExpression) -> bool {
call.arguments().map_or(false, |arguments| {
arguments.args().iter().all(|argument| {
argument.map_or(false, |argument| SimpleArgument::new(argument).is_simple())
})
})
}
/// In order to detect those cases, we use an heuristic: if the first
/// node is an identifier with the name starting with a capital
/// letter or just a sequence of _$. The rationale is that they are
/// likely to be factories.
fn is_factory(token: &JsSyntaxToken) -> bool {
let text = token.text_trimmed();
let mut chars = text.chars();
match text.chars().next() {
// Any sequence of '$' or '_' characters
Some('_') | Some('$') => chars.all(|c| matches!(c, '_' | '$')),
Some(c) => c.is_uppercase(),
_ => false,
}
}
/// Here we check if the length of the groups exceeds the cutoff or there are comments
/// This function is the inverse of the prettier function
/// [Prettier applies]: https://github.com/prettier/prettier/blob/a043ac0d733c4d53f980aa73807a63fc914f23bd/src/language-js/print/member-chain.js#L342
pub fn is_member_call_chain(
expression: JsCallExpression,
comments: &JsComments,
tab_width: TabWidth,
) -> SyntaxResult<bool> {
let chain = MemberChain::from_call_expression(expression, comments, tab_width)?;
Ok(chain.tail.is_member_call_chain(comments))
}
fn has_short_name(identifier: &JsIdentifierExpression, tab_width: TabWidth) -> bool {
identifier
.name()
.and_then(|name| name.value_token())
.map_or(false, |name| {
name.text_trimmed().len() <= u8::from(tab_width) as usize
})
}
struct ChainMembersIterator<'a> {
next: Option<AnyJsExpression>,
comments: &'a JsComments,
root: bool,
}
impl<'a> ChainMembersIterator<'a> {
fn new(root: AnyJsExpression, comments: &'a JsComments) -> Self {
Self {
next: Some(root),
comments,
root: true,
}
}
}
impl Iterator for ChainMembersIterator<'_> {
type Item = ChainMember;
fn next(&mut self) -> Option<Self::Item> {
use AnyJsExpression::*;
let expression = self.next.take()?;
if self.comments.is_suppressed(expression.syntax()) {
return Some(ChainMember::Node(expression.into_syntax()));
}
let member = match expression {
JsCallExpression(call_expression) => {
let callee = call_expression.callee().ok();
let is_chain = matches!(
callee,
Some(
JsStaticMemberExpression(_)
| JsComputedMemberExpression(_)
| JsCallExpression(_)
)
);
if is_chain {
self.next = callee;
}
let position = if self.root {
CallExpressionPosition::End
} else if !is_chain {
CallExpressionPosition::Start
} else {
CallExpressionPosition::Middle
};
ChainMember::CallExpression {
expression: call_expression,
position,
}
}
JsStaticMemberExpression(static_member) => {
self.next = static_member.object().ok();
ChainMember::StaticMember {
expression: static_member,
}
}
JsComputedMemberExpression(computed_expression) => {
self.next = computed_expression.object().ok();
ChainMember::ComputedMember {
expression: computed_expression,
}
}
TsNonNullAssertionExpression(expression) => {
self.next = expression.expression().ok();
ChainMember::TsNonNullAssertionExpression { expression }
}
expression => ChainMember::Node(expression.into_syntax()),
};
self.root = false;
Some(member)
}
}
impl FusedIterator for ChainMembersIterator<'_> {}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/utils/member_chain/groups.rs | crates/rome_js_formatter/src/utils/member_chain/groups.rs | use crate::parentheses::NeedsParentheses;
use crate::prelude::*;
use crate::utils::member_chain::chain_member::ChainMember;
use rome_formatter::write;
use std::cell::RefCell;
#[derive(Default)]
pub(super) struct MemberChainGroupsBuilder {
/// keeps track of the groups created
groups: Vec<MemberChainGroup>,
/// keeps track of the current group that is being created/updated
current_group: Option<MemberChainGroup>,
}
impl MemberChainGroupsBuilder {
/// starts a new group
pub fn start_group(&mut self, member: ChainMember) {
debug_assert!(self.current_group.is_none());
let mut group = MemberChainGroup::default();
group.members.push(member);
self.current_group = Some(group);
}
/// continues of starts a new group
pub fn start_or_continue_group(&mut self, member: ChainMember) {
match &mut self.current_group {
None => self.start_group(member),
Some(group) => group.members.push(member),
}
}
/// adds the passed element to the current group.
///
/// # Panics
///
/// If there's no started group.
pub fn continue_group(&mut self, member: ChainMember) {
match &mut self.current_group {
None => {
panic!("It is necessary to start a group first using `start_group`.");
}
Some(group) => {
group.members.push(member);
}
}
}
/// clears the current group, and adds it to the groups collection
pub fn close_group(&mut self) {
if let Some(group) = self.current_group.take() {
self.groups.push(group);
}
}
pub(super) fn finish(self) -> TailChainGroups {
let mut groups = self.groups;
if let Some(group) = self.current_group {
groups.push(group);
}
TailChainGroups { groups }
}
}
/// Groups following on the head group.
///
/// May be empty if all members are part of the head group
#[derive(Clone, Debug)]
pub(super) struct TailChainGroups {
groups: Vec<MemberChainGroup>,
}
impl TailChainGroups {
/// Returns `true` if there are no tail groups.
pub(crate) fn is_empty(&self) -> bool {
self.groups.is_empty()
}
/// Returns the number of tail groups.
pub(crate) fn len(&self) -> usize {
self.groups.len()
}
/// Returns the first group
pub(crate) fn first(&self) -> Option<&MemberChainGroup> {
self.groups.first()
}
/// Returns the last group
pub(crate) fn last(&self) -> Option<&MemberChainGroup> {
self.groups.last()
}
/// Removes the first group and returns it
pub(super) fn pop_first(&mut self) -> Option<MemberChainGroup> {
match self.groups.len() {
0 => None,
_ => Some(self.groups.remove(0)),
}
}
/// Checks if the groups contain comments.
pub fn has_comments(&self, comments: &JsComments) -> bool {
let mut members = self.groups.iter().flat_map(|item| item.members.iter());
let has_comments = members.any(|item| {
comments.has_trailing_comments(item.syntax())
|| comments.has_leading_comments(item.syntax())
});
let cutoff_has_leading_comments = if !self.groups.is_empty() {
let group = self.groups.get(1);
if let Some(group) = group {
let first_item = group.members.first();
first_item.map_or(false, |first_item| {
comments.has_leading_comments(first_item.syntax())
})
} else {
false
}
} else {
false
};
has_comments || cutoff_has_leading_comments
}
/// Here we check if the length of the groups exceeds the cutoff or there are comments
/// This function is the inverse of the prettier function
/// [Prettier applies]: https://github.com/prettier/prettier/blob/a043ac0d733c4d53f980aa73807a63fc914f23bd/src/language-js/print/member-chain.js#L342
pub(crate) fn is_member_call_chain(&self, comments: &JsComments) -> bool {
self.groups.len() > 1 || self.has_comments(comments)
}
/// Returns an iterator over the groups.
pub(super) fn iter(&self) -> impl Iterator<Item = &MemberChainGroup> + DoubleEndedIterator {
self.groups.iter()
}
/// Test if any group except the last group [break](FormatElements::will_break).
pub(super) fn any_except_last_will_break(&self, f: &mut JsFormatter) -> FormatResult<bool> {
for group in &self.groups[..self.groups.len().saturating_sub(1)] {
if group.will_break(f)? {
return Ok(true);
}
}
Ok(false)
}
/// Returns an iterator over all members
pub(super) fn members(&self) -> impl Iterator<Item = &ChainMember> + DoubleEndedIterator {
self.groups.iter().flat_map(|group| group.members().iter())
}
}
impl Format<JsFormatContext> for TailChainGroups {
fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
f.join().entries(self.groups.iter()).finish()
}
}
#[derive(Clone, Default)]
pub(super) struct MemberChainGroup {
members: Vec<ChainMember>,
/// Stores the formatted result of this group.
///
/// Manual implementation of `Memoized` to only memorizing the formatted result
/// if [MemberChainGroup::will_break] is called but not otherwise.
formatted: RefCell<Option<FormatElement>>,
}
impl MemberChainGroup {
pub(super) fn into_members(self) -> Vec<ChainMember> {
self.members
}
/// Returns the chain members of the group.
pub(super) fn members(&self) -> &[ChainMember] {
&self.members
}
/// Extends the members of this group with the passed in members
pub(super) fn extend_members(&mut self, members: impl IntoIterator<Item = ChainMember>) {
self.members.extend(members)
}
/// Tests if the formatted result of this group results in a [break](FormatElements::will_break).
pub(super) fn will_break(&self, f: &mut JsFormatter) -> FormatResult<bool> {
let mut cell = self.formatted.borrow_mut();
let result = match cell.as_ref() {
Some(formatted) => formatted.will_break(),
None => {
let interned = f.intern(&FormatMemberChainGroup { group: self })?;
if let Some(interned) = interned {
let breaks = interned.will_break();
*cell = Some(interned);
breaks
} else {
false
}
}
};
Ok(result)
}
pub(super) fn has_comments(&self, comments: &JsComments) -> bool {
self.members.iter().enumerate().any(|(index, member)| {
if index == 0 {
comments.has_trailing_comments(member.syntax())
} else if index < self.members.len() {
comments.has_leading_comments(member.syntax())
|| comments.has_trailing_comments(member.syntax())
} else {
false
}
})
}
}
impl From<Vec<ChainMember>> for MemberChainGroup {
fn from(entries: Vec<ChainMember>) -> Self {
Self {
members: entries,
formatted: RefCell::new(None),
}
}
}
impl std::fmt::Debug for MemberChainGroup {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("MemberChainGroup")
.field(&self.members)
.finish()
}
}
impl Format<JsFormatContext> for MemberChainGroup {
fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
if let Some(formatted) = self.formatted.borrow().as_ref() {
return f.write_element(formatted.clone());
}
FormatMemberChainGroup { group: self }.fmt(f)
}
}
pub struct FormatMemberChainGroup<'a> {
group: &'a MemberChainGroup,
}
impl Format<JsFormatContext> for FormatMemberChainGroup<'_> {
fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
let group = self.group;
let last = group.members.last();
let needs_parens = last.map_or(false, |last| match last {
ChainMember::StaticMember { expression, .. } => expression.needs_parentheses(),
ChainMember::ComputedMember { expression, .. } => expression.needs_parentheses(),
_ => false,
});
let format_entries = format_with(|f| f.join().entries(group.members.iter()).finish());
if needs_parens {
write!(f, [text("("), format_entries, text(")")])
} else {
write!(f, [format_entries])
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_formatter/src/utils/member_chain/simple_argument.rs | crates/rome_js_formatter/src/utils/member_chain/simple_argument.rs | use crate::utils::is_call_like_expression;
use rome_js_syntax::{
AnyJsArrayElement, AnyJsCallArgument, AnyJsExpression, AnyJsName, AnyJsObjectMember,
AnyJsObjectMemberName, AnyJsTemplateElement, JsSpread, JsStaticMemberExpressionFields,
JsTemplateExpression, JsUnaryOperator,
};
use rome_rowan::{AstSeparatedList, SyntaxResult};
/// This enum tracks the arguments inside a call expressions and checks if they are
/// simple or not.
///
/// The heuristic changes based on its type and the depth of the expressions. For example
/// if we have expressions as arguments, having 2 or more them tags the first argument as "not simple".
///
/// Criteria are different:
/// - *complex*: if the chain of simple arguments exceeds the depth 2 or higher
/// - *simple*: the argument is a literal
/// - *simple*: the argument is a [JsThisExpression]
/// - *simple*: the argument is a [JsIdentifierExpression]
/// - *simple*: the argument is a [JsSuperExpression]
/// - *simple*: the argument is a [JsUnaryExpression], has `!` or `-` operator and the argument is simple
/// - *simple*: the argument is a [TsNonNullAssertionExpression] and the argument is simple
/// - if the argument is a template literal, check [is_simple_template_literal]
/// - if the argument is an object expression, all its members are checked if they are simple or not. Check [is_simple_static_member_expression]
/// - if the argument is an array expression, all its elements are checked if they are simple or not. Check [is_simple_array_expression]
///
/// This algorithm is inspired from [Prettier].
///
/// [JsThisExpression]: [rome_js_syntax::JsThisExpression]
/// [JsIdentifierExpression]: [rome_js_syntax::JsIdentifierExpression]
/// [JsSuperExpression]: [rome_js_syntax::JsSuperExpression]
/// [is_simple_static_member_expression]: [Simple::is_simple_static_member_expression]
/// [is_simple_array_expression]: [Simple::is_simple_array_expression]
/// [JsUnaryExpression]: [rome_js_syntax::JsUnaryExpression]
/// [TsNonNullAssertionExpression]: [rome_js_syntax::TsNonNullAssertionExpression]
/// [Prettier]: https://github.com/prettier/prettier/blob/a9de2a128cc8eea84ddd90efdc210378a894ab6b/src/language-js/utils/index.js#L802-L886
#[derive(Debug)]
pub(crate) enum SimpleArgument {
Expression(AnyJsExpression),
Name(AnyJsName),
Spread,
}
impl SimpleArgument {
pub fn new(node: AnyJsCallArgument) -> Self {
match node {
AnyJsCallArgument::AnyJsExpression(expr) => Self::Expression(expr),
AnyJsCallArgument::JsSpread(_) => Self::Spread,
}
}
pub fn is_simple(&self) -> bool {
self.is_simple_impl(0)
}
fn is_simple_impl(&self, depth: u8) -> bool {
if depth >= 2 {
return false;
}
if self.is_simple_literal() {
return true;
}
self.is_simple_template(depth)
|| self.is_simple_object_expression(depth)
|| self.is_simple_array_expression(depth)
|| self.is_simple_unary_expression(depth).unwrap_or(false)
|| self
.is_simple_non_null_assertion_expression(depth)
.unwrap_or(false)
|| self
.is_simple_static_member_expression(depth)
.unwrap_or(false)
|| self.is_simple_call_like_expression(depth).unwrap_or(false)
|| self.is_simple_object_expression(depth)
}
fn is_simple_call_like_expression(&self, depth: u8) -> SyntaxResult<bool> {
let result = if let SimpleArgument::Expression(any_expression) = self {
if is_call_like_expression(any_expression) {
let mut is_import_call_expression = false;
let mut is_simple_callee = false;
let arguments = match any_expression {
AnyJsExpression::JsNewExpression(expr) => {
let callee = expr.callee()?;
is_simple_callee = SimpleArgument::from(callee).is_simple_impl(depth);
expr.arguments()
}
AnyJsExpression::JsCallExpression(expr) => {
let callee = expr.callee()?;
is_simple_callee = SimpleArgument::from(callee).is_simple_impl(depth);
expr.arguments().ok()
}
AnyJsExpression::JsImportCallExpression(expr) => {
is_import_call_expression = true;
expr.arguments().ok()
}
_ => unreachable!("The check is done inside `is_call_like_expression`"),
};
let simple_arguments = if let Some(arguments) = arguments {
arguments.args().iter().all(|argument| {
argument.map_or(true, |argument| {
SimpleArgument::from(argument).is_simple_impl(depth + 1)
})
})
} else {
true
};
(is_import_call_expression || is_simple_callee) && simple_arguments
} else {
false
}
} else {
false
};
Ok(result)
}
fn is_simple_static_member_expression(&self, depth: u8) -> SyntaxResult<bool> {
if let SimpleArgument::Expression(AnyJsExpression::JsStaticMemberExpression(
static_expression,
)) = self
{
let JsStaticMemberExpressionFields { member, object, .. } =
static_expression.as_fields();
Ok(member.is_ok() && SimpleArgument::from(object?).is_simple_impl(depth))
} else {
Ok(false)
}
}
fn is_simple_non_null_assertion_expression(&self, depth: u8) -> SyntaxResult<bool> {
if let SimpleArgument::Expression(AnyJsExpression::TsNonNullAssertionExpression(
assertion,
)) = self
{
Ok(SimpleArgument::from(assertion.expression()?).is_simple_impl(depth))
} else {
Ok(false)
}
}
fn is_simple_unary_expression(&self, depth: u8) -> SyntaxResult<bool> {
if let SimpleArgument::Expression(AnyJsExpression::JsUnaryExpression(unary_expression)) =
self
{
if matches!(
unary_expression.operator()?,
JsUnaryOperator::LogicalNot | JsUnaryOperator::Minus
) {
Ok(SimpleArgument::from(unary_expression.argument()?).is_simple_impl(depth))
} else {
Ok(false)
}
} else {
Ok(false)
}
}
fn is_simple_array_expression(&self, depth: u8) -> bool {
if let SimpleArgument::Expression(AnyJsExpression::JsArrayExpression(array_expression)) =
self
{
array_expression
.elements()
.iter()
.filter_map(|element| element.ok())
.all(|element| match element {
AnyJsArrayElement::AnyJsExpression(expression) => {
SimpleArgument::from(expression).is_simple_impl(depth + 1)
}
_ => false,
})
} else {
false
}
}
fn is_simple_template(&self, depth: u8) -> bool {
if let SimpleArgument::Expression(AnyJsExpression::JsTemplateExpression(template)) = self {
is_simple_template_literal(template, depth + 1).unwrap_or(false)
} else {
false
}
}
const fn is_simple_literal(&self) -> bool {
if let SimpleArgument::Name(AnyJsName::JsPrivateName(_)) = self {
return true;
}
matches!(
self,
SimpleArgument::Expression(
AnyJsExpression::AnyJsLiteralExpression(_)
| AnyJsExpression::JsThisExpression(_)
| AnyJsExpression::JsIdentifierExpression(_)
| AnyJsExpression::JsSuperExpression(_),
)
)
}
fn is_simple_object_expression(&self, depth: u8) -> bool {
if let SimpleArgument::Expression(AnyJsExpression::JsObjectExpression(object_expression)) =
self
{
object_expression
.members()
.iter()
.filter_map(|member| member.ok())
.all(|member| {
use AnyJsObjectMember::*;
match member {
JsShorthandPropertyObjectMember(_) => true,
JsPropertyObjectMember(property) => {
let is_computed = matches!(
property.name(),
Ok(AnyJsObjectMemberName::JsComputedMemberName(_))
);
let is_simple = property.value().map_or(false, |value| {
SimpleArgument::from(value).is_simple_impl(depth + 1)
});
!is_computed && is_simple
}
_ => false,
}
})
} else {
false
}
}
}
impl From<AnyJsExpression> for SimpleArgument {
fn from(expr: AnyJsExpression) -> Self {
Self::Expression(expr)
}
}
impl From<AnyJsName> for SimpleArgument {
fn from(name: AnyJsName) -> Self {
Self::Name(name)
}
}
impl From<JsSpread> for SimpleArgument {
fn from(_: JsSpread) -> Self {
Self::Spread
}
}
impl From<AnyJsCallArgument> for SimpleArgument {
fn from(call_argument: AnyJsCallArgument) -> Self {
match call_argument {
AnyJsCallArgument::AnyJsExpression(expr) => SimpleArgument::from(expr),
AnyJsCallArgument::JsSpread(spread) => SimpleArgument::from(spread),
}
}
}
/// A template literal is simple when:
///
/// - all strings dont contain newlines
/// - the expressions contained in the template are considered as `is_simple_call_argument`. Check
/// [is_simple_call_argument].
pub fn is_simple_template_literal(
template: &JsTemplateExpression,
depth: u8,
) -> SyntaxResult<bool> {
for element in template.elements() {
match element {
AnyJsTemplateElement::JsTemplateChunkElement(chunk) => {
if chunk.template_chunk_token()?.text_trimmed().contains('\n') {
return Ok(false);
}
}
AnyJsTemplateElement::JsTemplateElement(element) => {
let expression = element.expression()?;
if !(SimpleArgument::from(expression).is_simple_impl(depth)) {
return Ok(false);
}
}
}
}
Ok(true)
}
| 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/mod.rs | crates/rome_js_formatter/src/js/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 any;
pub(crate) mod assignments;
pub(crate) mod auxiliary;
pub(crate) mod bindings;
pub(crate) mod bogus;
pub(crate) mod classes;
pub(crate) mod declarations;
pub(crate) mod expressions;
pub(crate) mod lists;
pub(crate) mod module;
pub(crate) mod objects;
pub(crate) mod statements;
| 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/statements/for_in_statement.rs | crates/rome_js_formatter/src/js/statements/for_in_statement.rs | use crate::prelude::*;
use crate::utils::FormatStatementBody;
use rome_formatter::{format_args, write};
use rome_js_syntax::JsForInStatement;
use rome_js_syntax::JsForInStatementFields;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsForInStatement;
impl FormatNodeRule<JsForInStatement> for FormatJsForInStatement {
fn fmt_fields(&self, node: &JsForInStatement, f: &mut JsFormatter) -> FormatResult<()> {
let JsForInStatementFields {
for_token,
l_paren_token,
initializer,
in_token,
expression,
r_paren_token,
body,
} = node.as_fields();
let for_token = for_token.format();
let initializer = initializer.format();
let in_token = in_token.format();
let expression = expression.format();
write!(
f,
[group(&format_args!(
for_token,
space(),
l_paren_token.format(),
initializer,
space(),
in_token,
space(),
expression,
r_paren_token.format(),
FormatStatementBody::new(&body?)
))]
)
}
}
| 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/statements/break_statement.rs | crates/rome_js_formatter/src/js/statements/break_statement.rs | use crate::prelude::*;
use rome_formatter::write;
use crate::utils::FormatStatementSemicolon;
use rome_js_syntax::JsBreakStatement;
use rome_js_syntax::JsBreakStatementFields;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsBreakStatement;
impl FormatNodeRule<JsBreakStatement> for FormatJsBreakStatement {
fn fmt_fields(&self, node: &JsBreakStatement, f: &mut JsFormatter) -> FormatResult<()> {
let JsBreakStatementFields {
break_token,
label_token,
semicolon_token,
} = node.as_fields();
write!(f, [break_token.format()])?;
if let Some(label) = &label_token {
write!(f, [space(), label.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/statements/continue_statement.rs | crates/rome_js_formatter/src/js/statements/continue_statement.rs | use crate::prelude::*;
use rome_formatter::write;
use crate::utils::FormatStatementSemicolon;
use rome_js_syntax::JsContinueStatement;
use rome_js_syntax::JsContinueStatementFields;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsContinueStatement;
impl FormatNodeRule<JsContinueStatement> for FormatJsContinueStatement {
fn fmt_fields(&self, node: &JsContinueStatement, f: &mut JsFormatter) -> FormatResult<()> {
let JsContinueStatementFields {
continue_token,
label_token,
semicolon_token,
} = node.as_fields();
write!(f, [continue_token.format()])?;
if let Some(label) = &label_token {
write!(f, [space(), label.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/statements/do_while_statement.rs | crates/rome_js_formatter/src/js/statements/do_while_statement.rs | use crate::prelude::*;
use crate::utils::{FormatStatementBody, FormatStatementSemicolon};
use rome_formatter::{format_args, write};
use rome_js_syntax::JsDoWhileStatementFields;
use rome_js_syntax::{AnyJsStatement, JsDoWhileStatement};
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsDoWhileStatement;
impl FormatNodeRule<JsDoWhileStatement> for FormatJsDoWhileStatement {
fn fmt_fields(&self, node: &JsDoWhileStatement, f: &mut JsFormatter) -> FormatResult<()> {
let JsDoWhileStatementFields {
do_token,
body,
while_token,
l_paren_token,
test,
r_paren_token,
semicolon_token,
} = node.as_fields();
let body = body?;
let l_paren_token = l_paren_token?;
let r_paren_token = r_paren_token?;
write!(
f,
[group(&format_args![
do_token.format(),
FormatStatementBody::new(&body)
])]
)?;
if matches!(body, AnyJsStatement::JsBlockStatement(_)) {
write!(f, [space()])?;
} else {
write!(f, [hard_line_break()])?;
}
write!(
f,
[
while_token.format(),
space(),
l_paren_token.format(),
group(&soft_block_indent(&test.format())),
r_paren_token.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/statements/try_statement.rs | crates/rome_js_formatter/src/js/statements/try_statement.rs | use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::JsTryStatement;
use rome_js_syntax::JsTryStatementFields;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsTryStatement;
impl FormatNodeRule<JsTryStatement> for FormatJsTryStatement {
fn fmt_fields(&self, node: &JsTryStatement, f: &mut JsFormatter) -> FormatResult<()> {
let JsTryStatementFields {
try_token,
body,
catch_clause,
} = node.as_fields();
write![
f,
[
try_token.format(),
space(),
body.format(),
space(),
catch_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/statements/with_statement.rs | crates/rome_js_formatter/src/js/statements/with_statement.rs | use crate::prelude::*;
use rome_formatter::{format_args, write};
use crate::utils::FormatStatementBody;
use rome_js_syntax::JsWithStatement;
use rome_js_syntax::JsWithStatementFields;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsWithStatement;
impl FormatNodeRule<JsWithStatement> for FormatJsWithStatement {
fn fmt_fields(&self, node: &JsWithStatement, f: &mut JsFormatter) -> FormatResult<()> {
let JsWithStatementFields {
with_token,
l_paren_token,
object,
r_paren_token,
body,
} = node.as_fields();
write!(
f,
[group(&format_args![
with_token.format(),
space(),
l_paren_token.format(),
object.format(),
r_paren_token.format(),
FormatStatementBody::new(&body?)
])]
)
}
}
| 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/statements/debugger_statement.rs | crates/rome_js_formatter/src/js/statements/debugger_statement.rs | use crate::prelude::*;
use rome_formatter::write;
use crate::utils::FormatStatementSemicolon;
use rome_js_syntax::JsDebuggerStatement;
use rome_js_syntax::JsDebuggerStatementFields;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsDebuggerStatement;
impl FormatNodeRule<JsDebuggerStatement> for FormatJsDebuggerStatement {
fn fmt_fields(&self, node: &JsDebuggerStatement, f: &mut JsFormatter) -> FormatResult<()> {
let JsDebuggerStatementFields {
debugger_token,
semicolon_token,
} = node.as_fields();
write!(f, [debugger_token.format(),])?;
if f.comments().has_dangling_comments(node.syntax()) {
write!(f, [space(), format_dangling_comments(node.syntax())])?;
}
FormatStatementSemicolon::new(semicolon_token.as_ref()).fmt(f)
}
fn fmt_dangling_comments(
&self,
_: &JsDebuggerStatement,
_: &mut JsFormatter,
) -> FormatResult<()> {
// Handled in `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/statements/for_of_statement.rs | crates/rome_js_formatter/src/js/statements/for_of_statement.rs | use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::JsForOfStatement;
use crate::utils::FormatStatementBody;
use rome_js_syntax::JsForOfStatementFields;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsForOfStatement;
impl FormatNodeRule<JsForOfStatement> for FormatJsForOfStatement {
fn fmt_fields(&self, node: &JsForOfStatement, f: &mut JsFormatter) -> FormatResult<()> {
let JsForOfStatementFields {
for_token,
await_token,
l_paren_token,
initializer,
of_token,
expression,
r_paren_token,
body,
} = node.as_fields();
let body = body?;
let format_inner = format_with(|f| {
write!(f, [for_token.format()])?;
if let Some(await_token) = await_token.as_ref() {
write!(f, [space(), await_token.format()])?;
}
write!(
f,
[
space(),
l_paren_token.format(),
initializer.format(),
space(),
of_token.format(),
space(),
expression.format(),
r_paren_token.format(),
FormatStatementBody::new(&body)
]
)
});
write!(f, [group(&format_inner)])
}
}
| 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/statements/if_statement.rs | crates/rome_js_formatter/src/js/statements/if_statement.rs | use crate::prelude::*;
use rome_formatter::{format_args, write, CstFormatContext};
use crate::utils::FormatStatementBody;
use rome_js_syntax::JsIfStatement;
use rome_js_syntax::JsIfStatementFields;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsIfStatement;
impl FormatNodeRule<JsIfStatement> for FormatJsIfStatement {
fn fmt_fields(&self, node: &JsIfStatement, f: &mut JsFormatter) -> FormatResult<()> {
use rome_js_syntax::AnyJsStatement::*;
let JsIfStatementFields {
if_token,
l_paren_token,
test,
r_paren_token,
consequent,
else_clause,
} = node.as_fields();
let l_paren_token = l_paren_token?;
let r_paren_token = r_paren_token?;
let consequent = consequent?;
write!(
f,
[group(&format_args![
if_token.format(),
space(),
l_paren_token.format(),
group(&soft_block_indent(&test.format())),
r_paren_token.format(),
FormatStatementBody::new(&consequent),
]),]
)?;
if let Some(else_clause) = else_clause {
let comments = f.context().comments();
let dangling_comments = comments.dangling_comments(node.syntax());
let dangling_line_comment = dangling_comments
.last()
.map_or(false, |comment| comment.kind().is_line());
let has_dangling_comments = !dangling_comments.is_empty();
let trailing_line_comment = comments
.trailing_comments(consequent.syntax())
.iter()
.any(|comment| comment.kind().is_line());
let else_on_same_line = matches!(consequent, JsBlockStatement(_))
&& !trailing_line_comment
&& !dangling_line_comment;
if else_on_same_line {
write!(f, [space()])?;
} else {
write!(f, [hard_line_break()])?;
}
if has_dangling_comments {
write!(f, [format_dangling_comments(node.syntax())])?;
if trailing_line_comment || dangling_line_comment {
write!(f, [hard_line_break()])?
} else {
write!(f, [space()])?;
}
}
write!(f, [else_clause.format()])?;
}
Ok(())
}
fn fmt_dangling_comments(&self, _: &JsIfStatement, _: &mut JsFormatter) -> FormatResult<()> {
// Formatted 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/statements/return_statement.rs | crates/rome_js_formatter/src/js/statements/return_statement.rs | use crate::prelude::*;
use crate::utils::{AnyJsBinaryLikeExpression, FormatOptionalSemicolon, FormatStatementSemicolon};
use rome_formatter::{format_args, write, CstFormatContext};
use crate::parentheses::{get_expression_left_side, AnyJsExpressionLeftSide};
use rome_js_syntax::{
AnyJsExpression, JsReturnStatement, JsSequenceExpression, JsSyntaxToken, JsThrowStatement,
};
use rome_rowan::{declare_node_union, SyntaxResult};
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsReturnStatement;
impl FormatNodeRule<JsReturnStatement> for FormatJsReturnStatement {
fn fmt_fields(&self, node: &JsReturnStatement, f: &mut JsFormatter) -> FormatResult<()> {
AnyJsStatementWithArgument::from(node.clone()).fmt(f)
}
fn fmt_dangling_comments(
&self,
_: &JsReturnStatement,
_: &mut JsFormatter,
) -> FormatResult<()> {
// Formatted inside of `JsAnyStatementWithArgument`
Ok(())
}
}
declare_node_union! {
pub(super) AnyJsStatementWithArgument = JsThrowStatement | JsReturnStatement
}
impl Format<JsFormatContext> for AnyJsStatementWithArgument {
fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
write!(f, [self.operation_token().format()])?;
let argument = self.argument()?;
if let Some(semicolon) = self.semicolon_token() {
if let Some(argument) = argument {
write!(f, [space(), FormatReturnOrThrowArgument(&argument)])?;
}
let comments = f.context().comments();
let has_dangling_comments = comments.has_dangling_comments(self.syntax());
let is_last_comment_line = comments
.trailing_comments(self.syntax())
.last()
.or_else(|| comments.dangling_comments(self.syntax()).last())
.map_or(false, |comment| comment.kind().is_line());
if is_last_comment_line {
write!(f, [FormatOptionalSemicolon::new(Some(&semicolon))])?;
}
if has_dangling_comments {
write!(f, [space(), format_dangling_comments(self.syntax())])?;
}
if !is_last_comment_line {
write!(f, [FormatOptionalSemicolon::new(Some(&semicolon))])?;
}
Ok(())
} else {
if let Some(argument) = &argument {
write!(f, [space(), FormatReturnOrThrowArgument(argument)])?;
}
write!(f, [FormatStatementSemicolon::new(None)])
}
}
}
impl AnyJsStatementWithArgument {
fn operation_token(&self) -> SyntaxResult<JsSyntaxToken> {
match self {
AnyJsStatementWithArgument::JsThrowStatement(throw) => throw.throw_token(),
AnyJsStatementWithArgument::JsReturnStatement(ret) => ret.return_token(),
}
}
fn argument(&self) -> SyntaxResult<Option<AnyJsExpression>> {
match self {
AnyJsStatementWithArgument::JsThrowStatement(throw) => throw.argument().map(Some),
AnyJsStatementWithArgument::JsReturnStatement(ret) => Ok(ret.argument()),
}
}
fn semicolon_token(&self) -> Option<JsSyntaxToken> {
match self {
AnyJsStatementWithArgument::JsThrowStatement(throw) => throw.semicolon_token(),
AnyJsStatementWithArgument::JsReturnStatement(ret) => ret.semicolon_token(),
}
}
}
pub(super) struct FormatReturnOrThrowArgument<'a>(&'a AnyJsExpression);
impl Format<JsFormatContext> for FormatReturnOrThrowArgument<'_> {
fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
let argument = self.0;
let is_suppressed = f.comments().is_suppressed(argument.syntax());
if has_argument_leading_comments(argument, f.context().comments())
&& !matches!(argument, AnyJsExpression::JsxTagExpression(_))
&& !is_suppressed
{
write!(f, [text("("), &block_indent(&argument.format()), text(")")])
} else if is_binary_or_sequence_argument(argument) && !is_suppressed {
write!(
f,
[group(&format_args![
if_group_breaks(&text("(")),
soft_block_indent(&argument.format()),
if_group_breaks(&text(")"))
])]
)
} else {
write!(f, [argument.format()])
}
}
}
/// Tests if the passed in argument has any leading comments. This is the case if
/// * the argument has any leading comment
/// * the argument's left side has any leading comment (see [get_expression_left_side]).
///
/// Traversing the left nodes is necessary in case the first node is parenthesized because
/// parentheses will be removed (and be re-added by the return statement, but only if the argument breaks)
fn has_argument_leading_comments(argument: &AnyJsExpression, comments: &JsComments) -> bool {
let mut current: Option<AnyJsExpressionLeftSide> = Some(argument.clone().into());
while let Some(expression) = current {
if comments.has_leading_own_line_comment(expression.syntax()) {
return true;
}
current = get_expression_left_side(&expression);
}
false
}
fn is_binary_or_sequence_argument(argument: &AnyJsExpression) -> bool {
JsSequenceExpression::can_cast(argument.syntax().kind())
|| AnyJsBinaryLikeExpression::can_cast(argument.syntax().kind())
}
| 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/statements/variable_statement.rs | crates/rome_js_formatter/src/js/statements/variable_statement.rs | use crate::prelude::*;
use rome_formatter::write;
use crate::utils::FormatStatementSemicolon;
use rome_js_syntax::JsVariableStatement;
use rome_js_syntax::JsVariableStatementFields;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsVariableStatement;
impl FormatNodeRule<JsVariableStatement> for FormatJsVariableStatement {
fn fmt_fields(&self, node: &JsVariableStatement, f: &mut JsFormatter) -> FormatResult<()> {
let JsVariableStatementFields {
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/statements/while_statement.rs | crates/rome_js_formatter/src/js/statements/while_statement.rs | use crate::prelude::*;
use crate::utils::FormatStatementBody;
use rome_formatter::{format_args, write};
use rome_js_syntax::JsWhileStatement;
use rome_js_syntax::JsWhileStatementFields;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsWhileStatement;
impl FormatNodeRule<JsWhileStatement> for FormatJsWhileStatement {
fn fmt_fields(&self, node: &JsWhileStatement, f: &mut JsFormatter) -> FormatResult<()> {
let JsWhileStatementFields {
while_token,
l_paren_token,
test,
r_paren_token,
body,
} = node.as_fields();
write!(
f,
[group(&format_args![
while_token.format(),
space(),
l_paren_token.format(),
group(&soft_block_indent(&test.format())),
r_paren_token.format(),
FormatStatementBody::new(&body?)
])]
)
}
}
| 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/statements/mod.rs | crates/rome_js_formatter/src/js/statements/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 block_statement;
pub(crate) mod break_statement;
pub(crate) mod continue_statement;
pub(crate) mod debugger_statement;
pub(crate) mod do_while_statement;
pub(crate) mod empty_statement;
pub(crate) mod expression_statement;
pub(crate) mod for_in_statement;
pub(crate) mod for_of_statement;
pub(crate) mod for_statement;
pub(crate) mod if_statement;
pub(crate) mod labeled_statement;
pub(crate) mod return_statement;
pub(crate) mod switch_statement;
pub(crate) mod throw_statement;
pub(crate) mod try_finally_statement;
pub(crate) mod try_statement;
pub(crate) mod variable_statement;
pub(crate) mod while_statement;
pub(crate) mod with_statement;
| 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/statements/block_statement.rs | crates/rome_js_formatter/src/js/statements/block_statement.rs | use crate::prelude::*;
use rome_formatter::{write, Buffer, CstFormatContext};
use rome_js_syntax::JsBlockStatement;
use rome_js_syntax::{AnyJsStatement, JsEmptyStatement};
use rome_js_syntax::JsBlockStatementFields;
use rome_js_syntax::JsSyntaxKind;
use rome_rowan::{AstNode, AstNodeList, SyntaxNodeOptionExt};
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsBlockStatement;
impl FormatNodeRule<JsBlockStatement> for FormatJsBlockStatement {
fn fmt_fields(&self, node: &JsBlockStatement, f: &mut JsFormatter) -> FormatResult<()> {
let JsBlockStatementFields {
l_curly_token,
statements,
r_curly_token,
} = node.as_fields();
write!(f, [l_curly_token.format()])?;
let r_curly_token = r_curly_token?;
let comments = f.context().comments();
if is_empty_block(node, comments) {
let has_dangling_comments = comments.has_dangling_comments(node.syntax());
for stmt in statements
.iter()
.filter_map(|stmt| JsEmptyStatement::cast(stmt.into_syntax()))
{
f.state_mut().track_token(&stmt.semicolon_token()?)
}
if has_dangling_comments {
write!(
f,
[format_dangling_comments(node.syntax()).with_block_indent()]
)?;
} else if is_non_collapsible(node) {
write!(f, [hard_line_break()])?;
}
} else {
write!(f, [block_indent(&statements.format())])?;
}
write!(f, [r_curly_token.format()])
}
fn fmt_dangling_comments(&self, _: &JsBlockStatement, _: &mut JsFormatter) -> FormatResult<()> {
// Formatted inside of `fmt_fields`
Ok(())
}
}
fn is_empty_block(block: &JsBlockStatement, comments: &JsComments) -> bool {
// add extra branch to avoid formatting the same code twice and generating different code,
// here is an example:
// ```js
// try
// /* missing comment */
// {;}
// finally {}
// ```
// if we don't add the extra branch, this function will return false, because `block.statement` has one empty statement,
// and would be formatted as :
// ```js
// try
// /* missing comment */
// {}
// finally {}
// ```
// for the second time, the function would return true, because the block is empty and `parent.syntax.kind` is `JS_TRY_FINALLY_STATEMENT`, which would hit the branch `Some(_) => true`,
// finally the code would be formatted as:
// ```js
// try
/* missing comment */
// {
// } finally {
// }
// ```
block.statements().is_empty()
|| block.statements().iter().all(|s| {
matches!(s, AnyJsStatement::JsEmptyStatement(_))
&& !comments.has_comments(s.syntax())
&& !comments.is_suppressed(s.syntax())
})
}
// Formatting of curly braces for an:
// * empty block: same line `{}`,
// * empty block that is the 'cons' or 'alt' of an if statement: two lines `{\n}`
// * non empty block: put each stmt on its own line: `{\nstmt1;\nstmt2;\n}`
// * non empty block with comments (trailing comments on {, or leading comments on })
fn is_non_collapsible(block: &JsBlockStatement) -> bool {
// reference https://github.com/prettier/prettier/blob/b188c905cfaeb238a122b4a95c230da83f2f3226/src/language-js/print/block.js#L19
let parent = block.syntax().parent();
match parent.kind() {
Some(
JsSyntaxKind::JS_FUNCTION_BODY
| JsSyntaxKind::JS_FOR_STATEMENT
| JsSyntaxKind::JS_WHILE_STATEMENT
| JsSyntaxKind::JS_DO_WHILE_STATEMENT
| JsSyntaxKind::TS_MODULE_DECLARATION
| JsSyntaxKind::TS_DECLARE_FUNCTION_DECLARATION,
) => false,
// prettier collapse the catch block when it don't have `finalizer`, insert a new line when it has `finalizer`
Some(JsSyntaxKind::JS_CATCH_CLAUSE) => {
// SAFETY: since parent node have `Some(kind)`, this must not be `None`
let parent_unwrap = parent.unwrap();
let finally_clause = parent_unwrap.next_sibling();
matches!(
finally_clause.map(|finally| finally.kind()),
Some(JsSyntaxKind::JS_FINALLY_CLAUSE),
)
}
Some(_) => true,
None => 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/statements/throw_statement.rs | crates/rome_js_formatter/src/js/statements/throw_statement.rs | use crate::prelude::*;
use crate::js::statements::return_statement::AnyJsStatementWithArgument;
use rome_js_syntax::JsThrowStatement;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsThrowStatement;
impl FormatNodeRule<JsThrowStatement> for FormatJsThrowStatement {
fn fmt_fields(&self, node: &JsThrowStatement, f: &mut JsFormatter) -> FormatResult<()> {
AnyJsStatementWithArgument::from(node.clone()).fmt(f)
}
fn fmt_dangling_comments(&self, _: &JsThrowStatement, _: &mut JsFormatter) -> FormatResult<()> {
// Formatted inside of `JsAnyStatementWithArgument`
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/statements/expression_statement.rs | crates/rome_js_formatter/src/js/statements/expression_statement.rs | use crate::parentheses::{get_expression_left_side, AnyJsExpressionLeftSide, NeedsParentheses};
use crate::prelude::*;
use crate::utils::FormatStatementSemicolon;
use rome_formatter::{write, CstFormatContext};
use rome_js_syntax::{
AnyJsAssignment, AnyJsAssignmentPattern, AnyJsExpression, JsExpressionStatement, JsSyntaxKind,
JsUnaryOperator,
};
use rome_js_syntax::{AnyJsLiteralExpression, JsExpressionStatementFields};
use rome_rowan::SyntaxNodeOptionExt;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsExpressionStatement;
impl FormatNodeRule<JsExpressionStatement> for FormatJsExpressionStatement {
fn fmt_node(&self, node: &JsExpressionStatement, f: &mut JsFormatter) -> FormatResult<()> {
let needs_parentheses = self.needs_parentheses(node);
let is_after_bogus = f
.elements()
.start_tag(TagKind::Verbatim)
.map_or(false, |signal| match signal {
Tag::StartVerbatim(kind) => kind.is_bogus(),
_ => unreachable!(),
});
if f.options().semicolons().is_as_needed()
// Don't perform semicolon insertion if the previous statement is an bogus statement.
&& !is_after_bogus
&& (needs_parentheses || needs_semicolon(node))
{
write!(f, [text(";")])?;
}
if needs_parentheses {
write!(f, [text("(")])?;
}
self.fmt_fields(node, f)?;
if needs_parentheses {
write!(f, [text(")")])?;
}
Ok(())
}
fn fmt_fields(&self, node: &JsExpressionStatement, f: &mut JsFormatter) -> FormatResult<()> {
let JsExpressionStatementFields {
expression,
semicolon_token,
} = node.as_fields();
let has_dangling_comments = f.context().comments().has_dangling_comments(node.syntax());
write!(
f,
[
expression.format(),
FormatStatementSemicolon::new(semicolon_token.as_ref())
]
)?;
if has_dangling_comments {
write!(f, [space(), format_dangling_comments(node.syntax())])?;
}
Ok(())
}
fn fmt_dangling_comments(
&self,
_: &JsExpressionStatement,
_: &mut JsFormatter,
) -> FormatResult<()> {
// Formatted inside of `fmt_fields`
Ok(())
}
}
/// Returns `true` if a semicolon is required to keep the semantics of the program.
///
/// Semicolons are optional in most places in JavaScript, but they are sometimes required. Generally,
/// semicolons are necessary if an identifier + start of a statement may form a valid expression. For example:
///
/// ```javascript
/// a
/// ["b"]
/// ```
///
/// The above can either be the computed member expression `a["b"]` or the identifier `a` followed by an
/// expression statement `["b"]`.
///
/// Tokens that need a semicolon are:
///
/// * binary operators: `<`, `+`, `-`, ...
/// * `[` or `(`
/// * ticks: `\``
fn needs_semicolon(node: &JsExpressionStatement) -> bool {
use AnyJsExpression::*;
if !matches!(
node.syntax().parent().kind(),
Some(JsSyntaxKind::JS_MODULE_ITEM_LIST | JsSyntaxKind::JS_STATEMENT_LIST)
) {
return false;
}
let Ok(expression) = node.expression() else { return false };
let mut expression: Option<AnyJsExpressionLeftSide> = Some(expression.into());
while let Some(current) = expression.take() {
let needs_semi = match ¤t {
AnyJsExpressionLeftSide::AnyJsExpression(expression) => match expression {
JsArrayExpression(_)
| JsParenthesizedExpression(_)
| AnyJsLiteralExpression(self::AnyJsLiteralExpression::JsRegexLiteralExpression(
_,
))
| TsTypeAssertionExpression(_)
| JsArrowFunctionExpression(_)
| JsxTagExpression(_) => true,
JsTemplateExpression(template) => template.tag().is_none(),
JsUnaryExpression(unary) => matches!(
unary.operator(),
Ok(JsUnaryOperator::Plus | JsUnaryOperator::Minus)
),
_ => false,
},
AnyJsExpressionLeftSide::JsPrivateName(_) => false,
AnyJsExpressionLeftSide::AnyJsAssignmentPattern(assignment) => matches!(
assignment,
AnyJsAssignmentPattern::JsArrayAssignmentPattern(_)
| AnyJsAssignmentPattern::AnyJsAssignment(
AnyJsAssignment::JsParenthesizedAssignment(_),
)
| AnyJsAssignmentPattern::AnyJsAssignment(
AnyJsAssignment::TsTypeAssertionAssignment(_),
)
),
};
if needs_semi || current.needs_parentheses() {
return true;
}
expression = match get_expression_left_side(¤t) {
Some(inner) => Some(inner),
None => return false,
};
}
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/statements/switch_statement.rs | crates/rome_js_formatter/src/js/statements/switch_statement.rs | use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::{JsSwitchStatement, JsSwitchStatementFields};
use rome_rowan::AstNodeList;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsSwitchStatement;
impl FormatNodeRule<JsSwitchStatement> for FormatJsSwitchStatement {
fn fmt_fields(&self, node: &JsSwitchStatement, f: &mut JsFormatter) -> FormatResult<()> {
let JsSwitchStatementFields {
switch_token,
l_paren_token,
discriminant,
r_paren_token,
l_curly_token,
cases,
r_curly_token,
} = node.as_fields();
let format_cases = format_with(|f| {
if cases.is_empty() {
hard_line_break().fmt(f)?;
} else {
cases.format().fmt(f)?;
}
Ok(())
});
write![
f,
[
switch_token.format(),
space(),
l_paren_token.format(),
group(&soft_block_indent(&discriminant.format())),
r_paren_token.format(),
space(),
l_curly_token.format(),
block_indent(&format_cases),
r_curly_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/statements/for_statement.rs | crates/rome_js_formatter/src/js/statements/for_statement.rs | use crate::prelude::*;
use rome_formatter::{format_args, write, CstFormatContext};
use crate::utils::FormatStatementBody;
use rome_js_syntax::JsForStatement;
use rome_js_syntax::JsForStatementFields;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsForStatement;
impl FormatNodeRule<JsForStatement> for FormatJsForStatement {
fn fmt_fields(&self, node: &JsForStatement, f: &mut JsFormatter) -> FormatResult<()> {
let JsForStatementFields {
for_token,
l_paren_token,
initializer,
first_semi_token,
test,
second_semi_token,
update,
r_paren_token,
body,
} = node.as_fields();
let body = body?;
let l_paren_token = l_paren_token?;
let format_body = FormatStatementBody::new(&body);
// Move dangling trivia between the `for /* this */ (` to the top of the `for` and
// add a line break after.
let comments = f.context().comments();
let dangling_comments = comments.dangling_comments(node.syntax());
if !dangling_comments.is_empty() {
write!(
f,
[
format_dangling_comments(node.syntax()),
soft_line_break_or_space()
]
)?;
}
if initializer.is_none() && test.is_none() && update.is_none() {
return write!(
f,
[group(&format_args![
for_token.format(),
space(),
l_paren_token.format(),
first_semi_token.format(),
second_semi_token.format(),
r_paren_token.format(),
format_body
])]
);
}
let format_inner = format_with(|f| {
write!(
f,
[
for_token.format(),
space(),
l_paren_token.format(),
group(&soft_block_indent(&format_args![
initializer.format(),
first_semi_token.format(),
soft_line_break_or_space(),
test.format(),
second_semi_token.format(),
soft_line_break_or_space(),
update.format()
])),
r_paren_token.format(),
format_body
]
)
});
write!(f, [group(&format_inner)])
}
fn fmt_dangling_comments(&self, _: &JsForStatement, _: &mut JsFormatter) -> FormatResult<()> {
// Formatted 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/statements/labeled_statement.rs | crates/rome_js_formatter/src/js/statements/labeled_statement.rs | use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::JsLabeledStatementFields;
use rome_js_syntax::{AnyJsStatement, JsLabeledStatement};
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsLabeledStatement;
impl FormatNodeRule<JsLabeledStatement> for FormatJsLabeledStatement {
fn fmt_fields(&self, node: &JsLabeledStatement, f: &mut JsFormatter) -> FormatResult<()> {
let JsLabeledStatementFields {
label_token,
colon_token,
body,
} = node.as_fields();
write!(f, [label_token.format(), colon_token.format()])?;
match body? {
AnyJsStatement::JsEmptyStatement(empty) => {
// If the body is an empty statement, force semicolon insertion
write!(f, [empty.format(), text(";")])
}
body => {
write!(f, [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/statements/try_finally_statement.rs | crates/rome_js_formatter/src/js/statements/try_finally_statement.rs | use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::JsTryFinallyStatement;
use rome_js_syntax::JsTryFinallyStatementFields;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsTryFinallyStatement;
impl FormatNodeRule<JsTryFinallyStatement> for FormatJsTryFinallyStatement {
fn fmt_fields(&self, node: &JsTryFinallyStatement, f: &mut JsFormatter) -> FormatResult<()> {
let JsTryFinallyStatementFields {
try_token,
body,
catch_clause,
finally_clause,
} = node.as_fields();
write![f, [try_token.format(), space(), body.format()]]?;
if let Some(catch_clause) = catch_clause {
write!(f, [space(), catch_clause.format()])?;
}
write!(f, [space(), finally_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/statements/empty_statement.rs | crates/rome_js_formatter/src/js/statements/empty_statement.rs | use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::{JsEmptyStatement, JsEmptyStatementFields, JsSyntaxKind};
use rome_rowan::{AstNode, SyntaxNodeOptionExt};
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsEmptyStatement;
impl FormatNodeRule<JsEmptyStatement> for FormatJsEmptyStatement {
fn fmt_fields(&self, node: &JsEmptyStatement, f: &mut JsFormatter) -> FormatResult<()> {
let JsEmptyStatementFields { semicolon_token } = node.as_fields();
let parent_kind = node.syntax().parent().kind();
if matches!(
parent_kind,
Some(
JsSyntaxKind::JS_DO_WHILE_STATEMENT
| JsSyntaxKind::JS_IF_STATEMENT
| JsSyntaxKind::JS_ELSE_CLAUSE
| JsSyntaxKind::JS_WHILE_STATEMENT
| JsSyntaxKind::JS_FOR_IN_STATEMENT
| JsSyntaxKind::JS_FOR_OF_STATEMENT
| JsSyntaxKind::JS_FOR_STATEMENT
| JsSyntaxKind::JS_WITH_STATEMENT
)
) {
write!(f, [semicolon_token.format()])
} else {
write!(f, [format_removed(&semicolon_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/lists/decorator_list.rs | crates/rome_js_formatter/src/js/lists/decorator_list.rs | use crate::prelude::*;
use crate::utils::format_modifiers::should_expand_decorators;
use rome_formatter::write;
use rome_js_syntax::JsSyntaxKind::{
JS_CLASS_EXPRESSION, JS_FORMAL_PARAMETER, JS_REST_PARAMETER, TS_PROPERTY_PARAMETER,
};
use rome_js_syntax::{
AnyJsDeclarationClause, AnyJsExportClause, AnyJsExportDefaultDeclaration, JsDecoratorList,
JsExport,
};
use rome_rowan::SyntaxNodeOptionExt;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsDecoratorList;
impl FormatRule<JsDecoratorList> for FormatJsDecoratorList {
type Context = JsFormatContext;
fn fmt(&self, node: &JsDecoratorList, f: &mut JsFormatter) -> FormatResult<()> {
if node.is_empty() {
return Ok(());
}
// we need to rearrange decorators to be before export if we have decorators before class and after export
if let Some(export) = node.parent::<JsExport>() {
let mut join = f.join_nodes_with_hardline();
// write decorators before export first
for decorator in node {
join.entry(decorator.syntax(), &format_or_verbatim(decorator.format()));
}
// try to find class decorators
let class_decorators = match export.export_clause()? {
AnyJsExportClause::AnyJsDeclarationClause(
AnyJsDeclarationClause::JsClassDeclaration(class),
) => {
// @before export @after class Foo {}
Some(class.decorators())
}
AnyJsExportClause::JsExportDefaultDeclarationClause(export_default_declaration) => {
match export_default_declaration.declaration()? {
AnyJsExportDefaultDeclaration::JsClassExportDefaultDeclaration(class) => {
// @before export default @after class Foo {}
Some(class.decorators())
}
_ => None,
}
}
_ => None,
};
// write decorators after export
if let Some(class_decorators) = class_decorators {
for decorator in class_decorators {
join.entry(decorator.syntax(), &format_or_verbatim(decorator.format()));
}
}
join.finish()?;
write!(f, [hard_line_break()])
} else if matches!(node.syntax().parent().kind(), Some(JS_CLASS_EXPRESSION)) {
write!(f, [expand_parent()])?;
f.join_with(&soft_line_break_or_space())
.entries(node.iter().formatted())
.finish()?;
write!(f, [soft_line_break_or_space()])
} else {
let is_parameter_decorators = matches!(
node.syntax().parent().kind(),
Some(JS_FORMAL_PARAMETER | JS_REST_PARAMETER | TS_PROPERTY_PARAMETER)
);
if is_parameter_decorators {
let should_expand = should_expand_decorators(node);
if should_expand {
write!(f, [expand_parent()])?;
}
} else {
// If the parent node is an export declaration and the decorator
// was written before the export, the export will be responsible
// for printing the decorators.
let export = node.syntax().grand_parent().and_then(|grand_parent| {
JsExport::cast_ref(&grand_parent)
.or_else(|| grand_parent.parent().and_then(JsExport::cast))
});
let is_export = export.is_some();
let has_decorators_before_export =
export.map_or(false, |export| !export.decorators().is_empty());
if has_decorators_before_export {
return Ok(());
}
if is_export {
write!(f, [hard_line_break()])?;
} else {
write!(f, [expand_parent()])?;
}
}
f.join_with(&soft_line_break_or_space())
.entries(node.iter().formatted())
.finish()?;
write!(f, [soft_line_break_or_space()])
}
}
}
| 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/lists/array_assignment_pattern_element_list.rs | crates/rome_js_formatter/src/js/lists/array_assignment_pattern_element_list.rs | use crate::prelude::*;
use crate::utils::array::write_array_node;
use rome_js_syntax::JsArrayAssignmentPatternElementList;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsArrayAssignmentPatternElementList;
impl FormatRule<JsArrayAssignmentPatternElementList> for FormatJsArrayAssignmentPatternElementList {
type Context = JsFormatContext;
fn fmt(
&self,
node: &JsArrayAssignmentPatternElementList,
formatter: &mut JsFormatter,
) -> FormatResult<()> {
write_array_node(node, formatter)
}
}
| 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/lists/export_named_specifier_list.rs | crates/rome_js_formatter/src/js/lists/export_named_specifier_list.rs | use crate::context::trailing_comma::FormatTrailingComma;
use crate::prelude::*;
use rome_js_syntax::JsExportNamedSpecifierList;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsExportNamedSpecifierList;
impl FormatRule<JsExportNamedSpecifierList> for FormatJsExportNamedSpecifierList {
type Context = JsFormatContext;
fn fmt(&self, node: &JsExportNamedSpecifierList, f: &mut JsFormatter) -> FormatResult<()> {
let trailing_separator = FormatTrailingComma::ES5.trailing_separator(f.options());
f.join_with(&soft_line_break_or_space())
.entries(
node.format_separated(",")
.with_trailing_separator(trailing_separator),
)
.finish()
}
}
| 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/lists/constructor_parameter_list.rs | crates/rome_js_formatter/src/js/lists/constructor_parameter_list.rs | use crate::js::bindings::parameters::ParameterLayout;
use crate::js::lists::parameter_list::FormatJsAnyParameterList;
use crate::prelude::*;
use rome_js_syntax::parameter_ext::AnyJsParameterList;
use rome_js_syntax::JsConstructorParameterList;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsConstructorParameterList;
impl FormatRule<JsConstructorParameterList> for FormatJsConstructorParameterList {
type Context = JsFormatContext;
fn fmt(&self, node: &JsConstructorParameterList, f: &mut JsFormatter) -> FormatResult<()> {
FormatJsAnyParameterList::with_layout(
&AnyJsParameterList::from(node.clone()),
ParameterLayout::Default,
)
.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/lists/object_member_list.rs | crates/rome_js_formatter/src/js/lists/object_member_list.rs | use crate::context::trailing_comma::FormatTrailingComma;
use crate::prelude::*;
use rome_js_syntax::JsObjectMemberList;
use rome_rowan::{AstNode, AstSeparatedList};
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsObjectMemberList;
impl FormatRule<JsObjectMemberList> for FormatJsObjectMemberList {
type Context = JsFormatContext;
fn fmt(&self, node: &JsObjectMemberList, f: &mut JsFormatter) -> FormatResult<()> {
let trailing_separator = FormatTrailingComma::ES5.trailing_separator(f.options());
let mut join = f.join_nodes_with_soft_line();
for (element, formatted) in node.elements().zip(
node.format_separated(",")
.with_trailing_separator(trailing_separator),
) {
join.entry(element.node()?.syntax(), &formatted);
}
join.finish()
}
}
| 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/lists/statement_list.rs | crates/rome_js_formatter/src/js/lists/statement_list.rs | use crate::prelude::*;
use rome_js_syntax::{AnyJsStatement, JsStatementList};
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsStatementList;
impl FormatRule<JsStatementList> for FormatJsStatementList {
type Context = JsFormatContext;
fn fmt(&self, node: &JsStatementList, f: &mut JsFormatter) -> FormatResult<()> {
let mut join = f.join_nodes_with_hardline();
for statement in node.iter() {
match statement {
AnyJsStatement::JsEmptyStatement(empty) => {
join.entry_no_separator(&empty.format());
}
_ => {
join.entry(statement.syntax(), &format_or_verbatim(statement.format()));
}
}
}
join.finish()
}
}
| 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/lists/export_named_from_specifier_list.rs | crates/rome_js_formatter/src/js/lists/export_named_from_specifier_list.rs | use crate::context::trailing_comma::FormatTrailingComma;
use crate::prelude::*;
use rome_js_syntax::JsExportNamedFromSpecifierList;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsExportNamedFromSpecifierList;
impl FormatRule<JsExportNamedFromSpecifierList> for FormatJsExportNamedFromSpecifierList {
type Context = JsFormatContext;
fn fmt(&self, node: &JsExportNamedFromSpecifierList, f: &mut JsFormatter) -> FormatResult<()> {
let trailing_separator = FormatTrailingComma::ES5.trailing_separator(f.options());
f.join_with(&soft_line_break_or_space())
.entries(
node.format_separated(",")
.with_trailing_separator(trailing_separator),
)
.finish()
}
}
| 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/lists/array_element_list.rs | crates/rome_js_formatter/src/js/lists/array_element_list.rs | use crate::prelude::*;
use rome_formatter::{write, CstFormatContext, FormatRuleWithOptions, GroupId};
use crate::utils::array::write_array_node;
use crate::context::trailing_comma::FormatTrailingComma;
use rome_js_syntax::JsArrayElementList;
use rome_rowan::{AstNode, AstSeparatedList};
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsArrayElementList {
group_id: Option<GroupId>,
}
impl FormatRuleWithOptions<JsArrayElementList> for FormatJsArrayElementList {
type Options = Option<GroupId>;
fn with_options(mut self, options: Self::Options) -> Self {
self.group_id = options;
self
}
}
impl FormatRule<JsArrayElementList> for FormatJsArrayElementList {
type Context = JsFormatContext;
fn fmt(&self, node: &JsArrayElementList, f: &mut JsFormatter) -> FormatResult<()> {
let layout = if can_concisely_print_array_list(node, f.context().comments()) {
ArrayLayout::Fill
} else {
ArrayLayout::OnePerLine
};
match layout {
ArrayLayout::Fill => {
let trailing_separator = FormatTrailingComma::ES5.trailing_separator(f.options());
let mut filler = f.fill();
// Using format_separated is valid in this case as can_print_fill does not allow holes
for (element, formatted) in node.iter().zip(
node.format_separated(",")
.with_trailing_separator(trailing_separator)
.with_group_id(self.group_id),
) {
filler.entry(
&format_once(|f| {
if get_lines_before(element?.syntax()) > 1 {
write!(f, [empty_line()])
} else {
write!(f, [soft_line_break_or_space()])
}
}),
&formatted,
);
}
filler.finish()
}
ArrayLayout::OnePerLine => write_array_node(node, f),
}
}
}
#[derive(Copy, Clone, Debug)]
enum ArrayLayout {
/// Tries to fit as many array elements on a single line as possible.
///
/// ```javascript
/// [
/// 1, 2, 3,
/// 5, 6,
/// ]
/// ```
Fill,
/// Prints every element on a single line if the whole array expression exceeds the line width, or any
/// of its elements gets printed in *expanded* mode.
/// ```javascript
/// [
/// a.b(),
/// 4,
/// 3,
/// ]
/// ```
OnePerLine,
}
/// Returns true if the provided JsArrayElementList could
/// be "fill-printed" instead of breaking each element on
/// a different line.
///
/// The underlying logic only allows lists of literal expressions
/// with 10 or less characters, potentially wrapped in a "short"
/// unary expression (+, -, ~ or !)
pub(crate) fn can_concisely_print_array_list(
list: &JsArrayElementList,
comments: &JsComments,
) -> bool {
use rome_js_syntax::AnyJsArrayElement::*;
use rome_js_syntax::AnyJsExpression::*;
use rome_js_syntax::JsUnaryOperator::*;
if list.is_empty() {
return false;
}
list.elements().all(|item| {
let syntax = match item.into_node() {
Ok(AnyJsExpression(AnyJsLiteralExpression(
rome_js_syntax::AnyJsLiteralExpression::JsNumberLiteralExpression(literal),
))) => literal.into_syntax(),
Ok(AnyJsExpression(JsUnaryExpression(expr))) => {
let signed = matches!(expr.operator(), Ok(Plus | Minus));
let argument = expr.argument();
match argument {
Ok(AnyJsLiteralExpression(
rome_js_syntax::AnyJsLiteralExpression::JsNumberLiteralExpression(literal),
)) => {
if signed && !comments.has_comments(literal.syntax()) {
expr.into_syntax()
} else {
return false;
}
}
_ => {
return false;
}
}
}
_ => {
return false;
}
};
// Does not have a line comment ending on the same line
// ```javascript
// [ a // not this
// b];
//
// [
// // This is fine
// thats
// ]
// ```
!comments
.trailing_comments(&syntax)
.iter()
.filter(|comment| comment.kind().is_line())
.any(|comment| comment.lines_before() == 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/lists/array_binding_pattern_element_list.rs | crates/rome_js_formatter/src/js/lists/array_binding_pattern_element_list.rs | use crate::prelude::*;
use crate::utils::array::write_array_node;
use rome_js_syntax::JsArrayBindingPatternElementList;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsArrayBindingPatternElementList;
impl FormatRule<JsArrayBindingPatternElementList> for FormatJsArrayBindingPatternElementList {
type Context = JsFormatContext;
fn fmt(
&self,
node: &JsArrayBindingPatternElementList,
formatter: &mut JsFormatter,
) -> FormatResult<()> {
write_array_node(node, formatter)
}
}
| 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/lists/import_assertion_entry_list.rs | crates/rome_js_formatter/src/js/lists/import_assertion_entry_list.rs | use crate::context::trailing_comma::FormatTrailingComma;
use crate::prelude::*;
use rome_js_syntax::JsImportAssertionEntryList;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsImportAssertionEntryList;
impl FormatRule<JsImportAssertionEntryList> for FormatJsImportAssertionEntryList {
type Context = JsFormatContext;
fn fmt(&self, node: &JsImportAssertionEntryList, f: &mut JsFormatter) -> FormatResult<()> {
let trailing_separator = FormatTrailingComma::ES5.trailing_separator(f.options());
f.join_with(&soft_line_break_or_space())
.entries(
node.format_separated(",")
.with_trailing_separator(trailing_separator),
)
.finish()
}
}
| 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/lists/property_modifier_list.rs | crates/rome_js_formatter/src/js/lists/property_modifier_list.rs | use crate::prelude::*;
use crate::utils::format_modifiers::FormatModifiers;
use rome_js_syntax::JsPropertyModifierList;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsPropertyModifierList;
impl FormatRule<JsPropertyModifierList> for FormatJsPropertyModifierList {
type Context = JsFormatContext;
fn fmt(&self, node: &JsPropertyModifierList, f: &mut JsFormatter) -> FormatResult<()> {
FormatModifiers::from(node.clone()).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/lists/parameter_list.rs | crates/rome_js_formatter/src/js/lists/parameter_list.rs | use crate::js::bindings::parameters::ParameterLayout;
use crate::prelude::*;
use crate::context::trailing_comma::FormatTrailingComma;
use rome_js_syntax::parameter_ext::{AnyJsParameterList, AnyParameter};
use rome_js_syntax::{AnyJsConstructorParameter, AnyJsParameter, JsParameterList};
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsParameterList;
impl FormatRule<JsParameterList> for FormatJsParameterList {
type Context = JsFormatContext;
fn fmt(&self, node: &JsParameterList, f: &mut JsFormatter) -> FormatResult<()> {
FormatJsAnyParameterList::with_layout(
&AnyJsParameterList::from(node.clone()),
ParameterLayout::Default,
)
.fmt(f)
}
}
#[derive(Debug, Copy, Clone)]
pub(crate) struct FormatJsAnyParameterList<'a> {
list: &'a AnyJsParameterList,
layout: Option<ParameterLayout>,
}
impl<'a> FormatJsAnyParameterList<'a> {
pub fn with_layout(list: &'a AnyJsParameterList, layout: ParameterLayout) -> Self {
Self {
list,
layout: Some(layout),
}
}
}
impl Format<JsFormatContext> for FormatJsAnyParameterList<'_> {
fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
match self.layout {
None | Some(ParameterLayout::Default) | Some(ParameterLayout::NoParameters) => {
// The trailing separator is disallowed if the last element in the list is a rest parameter
let has_trailing_rest = match self.list.last() {
Some(elem) => matches!(
elem?,
AnyParameter::AnyJsParameter(AnyJsParameter::JsRestParameter(_))
| AnyParameter::AnyJsConstructorParameter(
AnyJsConstructorParameter::JsRestParameter(_)
)
),
None => false,
};
let trailing_separator = if has_trailing_rest {
TrailingSeparator::Disallowed
} else {
FormatTrailingComma::All.trailing_separator(f.options())
};
let mut join = f.join_nodes_with_soft_line();
match self.list {
AnyJsParameterList::JsParameterList(list) => {
let entries = list
.format_separated(",")
.with_trailing_separator(trailing_separator)
.zip(list.iter());
for (format_entry, node) in entries {
join.entry(node?.syntax(), &format_entry);
}
}
AnyJsParameterList::JsConstructorParameterList(list) => {
let entries = list
.format_separated(",")
.with_trailing_separator(trailing_separator)
.zip(list.iter());
for (format_entry, node) in entries {
join.entry(node?.syntax(), &format_entry);
}
}
}
join.finish()
}
Some(ParameterLayout::Hug) => {
let mut join = f.join_with(space());
match self.list {
AnyJsParameterList::JsParameterList(list) => join.entries(
list.format_separated(",")
.with_trailing_separator(TrailingSeparator::Omit),
),
AnyJsParameterList::JsConstructorParameterList(list) => join.entries(
list.format_separated(",")
.with_trailing_separator(TrailingSeparator::Omit),
),
};
join.finish()
}
}
}
}
| 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/lists/mod.rs | crates/rome_js_formatter/src/js/lists/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_assignment_pattern_element_list;
pub(crate) mod array_binding_pattern_element_list;
pub(crate) mod array_element_list;
pub(crate) mod call_argument_list;
pub(crate) mod class_member_list;
pub(crate) mod constructor_modifier_list;
pub(crate) mod constructor_parameter_list;
pub(crate) mod decorator_list;
pub(crate) mod directive_list;
pub(crate) mod export_named_from_specifier_list;
pub(crate) mod export_named_specifier_list;
pub(crate) mod import_assertion_entry_list;
pub(crate) mod method_modifier_list;
pub(crate) mod module_item_list;
pub(crate) mod named_import_specifier_list;
pub(crate) mod object_assignment_pattern_property_list;
pub(crate) mod object_binding_pattern_property_list;
pub(crate) mod object_member_list;
pub(crate) mod parameter_list;
pub(crate) mod property_modifier_list;
pub(crate) mod statement_list;
pub(crate) mod switch_case_list;
pub(crate) mod template_element_list;
pub(crate) mod variable_declarator_list;
| 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/lists/module_item_list.rs | crates/rome_js_formatter/src/js/lists/module_item_list.rs | use crate::prelude::*;
use rome_js_syntax::{AnyJsModuleItem, AnyJsStatement, JsModuleItemList};
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsModuleItemList;
impl FormatRule<JsModuleItemList> for FormatJsModuleItemList {
type Context = JsFormatContext;
fn fmt(&self, node: &JsModuleItemList, f: &mut JsFormatter) -> FormatResult<()> {
let mut join = f.join_nodes_with_hardline();
for module_item in node {
match module_item {
AnyJsModuleItem::AnyJsStatement(AnyJsStatement::JsEmptyStatement(empty)) => {
join.entry_no_separator(&empty.format());
}
_ => {
join.entry(
module_item.syntax(),
&format_or_verbatim(module_item.format()),
);
}
}
}
join.finish()
}
}
| 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/lists/object_binding_pattern_property_list.rs | crates/rome_js_formatter/src/js/lists/object_binding_pattern_property_list.rs | use crate::context::trailing_comma::FormatTrailingComma;
use crate::prelude::*;
use rome_js_syntax::{AnyJsObjectBindingPatternMember, JsObjectBindingPatternPropertyList};
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsObjectBindingPatternPropertyList;
impl FormatRule<JsObjectBindingPatternPropertyList> for FormatJsObjectBindingPatternPropertyList {
type Context = JsFormatContext;
fn fmt(
&self,
node: &JsObjectBindingPatternPropertyList,
f: &mut JsFormatter,
) -> FormatResult<()> {
// The trailing separator is disallowed after a rest element
let has_trailing_rest = match node.into_iter().last() {
Some(elem) => matches!(
elem?,
AnyJsObjectBindingPatternMember::JsObjectBindingPatternRest(_)
),
None => false,
};
let trailing_separator = if has_trailing_rest {
TrailingSeparator::Disallowed
} else {
FormatTrailingComma::ES5.trailing_separator(f.options())
};
let entries = node
.format_separated(",")
.with_trailing_separator(trailing_separator)
.zip(node.iter());
let mut join = f.join_nodes_with_soft_line();
for (format_entry, node) in entries {
join.entry(node?.syntax(), &format_entry);
}
join.finish()
}
}
| 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/lists/call_argument_list.rs | crates/rome_js_formatter/src/js/lists/call_argument_list.rs | use crate::prelude::*;
use crate::utils::write_arguments_multi_line;
use rome_formatter::write;
use rome_js_syntax::JsCallArgumentList;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsCallArgumentList;
impl FormatRule<JsCallArgumentList> for FormatJsCallArgumentList {
type Context = JsFormatContext;
fn fmt(&self, node: &JsCallArgumentList, f: &mut JsFormatter) -> FormatResult<()> {
if node.len() == 0 {
return Ok(());
}
write!(
f,
[&group(&soft_block_indent(&format_with(|f| {
let separated = node
.format_separated(",")
.with_trailing_separator(TrailingSeparator::Omit);
write_arguments_multi_line(separated, 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/lists/class_member_list.rs | crates/rome_js_formatter/src/js/lists/class_member_list.rs | use crate::prelude::*;
use rome_js_syntax::JsClassMemberList;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsClassMemberList;
impl FormatRule<JsClassMemberList> for FormatJsClassMemberList {
type Context = JsFormatContext;
fn fmt(&self, node: &JsClassMemberList, f: &mut JsFormatter) -> FormatResult<()> {
let mut join = f.join_nodes_with_hardline();
for member in node {
join.entry(member.syntax(), &format_or_verbatim(member.format()));
}
join.finish()
}
}
| 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/lists/constructor_modifier_list.rs | crates/rome_js_formatter/src/js/lists/constructor_modifier_list.rs | use crate::prelude::*;
use rome_js_syntax::JsConstructorModifierList;
use rome_rowan::AstNodeList;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsConstructorModifierList;
impl FormatRule<JsConstructorModifierList> for FormatJsConstructorModifierList {
type Context = JsFormatContext;
fn fmt(&self, node: &JsConstructorModifierList, f: &mut JsFormatter) -> FormatResult<()> {
f.join_with(&space())
.entries(node.iter().formatted())
.finish()
}
}
| 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/lists/directive_list.rs | crates/rome_js_formatter/src/js/lists/directive_list.rs | use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::JsDirectiveList;
use rome_rowan::{AstNode, AstNodeList};
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsDirectiveList;
impl FormatRule<JsDirectiveList> for FormatJsDirectiveList {
type Context = JsFormatContext;
fn fmt(&self, node: &JsDirectiveList, f: &mut JsFormatter) -> FormatResult<()> {
if node.is_empty() {
return Ok(());
}
let syntax_node = node.syntax();
let next_sibling = syntax_node.next_sibling();
// if next_sibling's first leading_trivia has more than one new_line, we should add an extra empty line at the end of
// JsDirectiveList, for example:
//```js
// "use strict"; <- first leading new_line
// <- second leading new_line
// function foo() {
// }
//```
// so we should keep an extra empty line after JsDirectiveList
let need_extra_empty_line = if let Some(next_sibling) = next_sibling {
get_lines_before(&next_sibling) > 1
} else {
false
};
let mut join = f.join_nodes_with_hardline();
for directive in node {
join.entry(directive.syntax(), &directive.format());
}
join.finish()?;
if need_extra_empty_line {
write!(f, [empty_line()])
} else {
write!(f, [hard_line_break()])
}
}
}
| 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/lists/object_assignment_pattern_property_list.rs | crates/rome_js_formatter/src/js/lists/object_assignment_pattern_property_list.rs | use crate::context::trailing_comma::FormatTrailingComma;
use crate::prelude::*;
use rome_js_syntax::{AnyJsObjectAssignmentPatternMember, JsObjectAssignmentPatternPropertyList};
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsObjectAssignmentPatternPropertyList;
impl FormatRule<JsObjectAssignmentPatternPropertyList>
for FormatJsObjectAssignmentPatternPropertyList
{
type Context = JsFormatContext;
fn fmt(
&self,
node: &JsObjectAssignmentPatternPropertyList,
f: &mut JsFormatter,
) -> FormatResult<()> {
// The trailing separator is disallowed after a rest element
let has_trailing_rest = match node.into_iter().last() {
Some(elem) => matches!(
elem?,
AnyJsObjectAssignmentPatternMember::JsObjectAssignmentPatternRest(_)
),
None => false,
};
let trailing_separator = if has_trailing_rest {
TrailingSeparator::Disallowed
} else {
FormatTrailingComma::ES5.trailing_separator(f.options())
};
let entries = node
.format_separated(",")
.with_trailing_separator(trailing_separator)
.zip(node.iter());
let mut join = f.join_nodes_with_soft_line();
for (format_entry, node) in entries {
join.entry(node?.syntax(), &format_entry);
}
join.finish()
}
}
| 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/lists/named_import_specifier_list.rs | crates/rome_js_formatter/src/js/lists/named_import_specifier_list.rs | use crate::context::trailing_comma::FormatTrailingComma;
use crate::prelude::*;
use rome_js_syntax::JsNamedImportSpecifierList;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsNamedImportSpecifierList;
impl FormatRule<JsNamedImportSpecifierList> for FormatJsNamedImportSpecifierList {
type Context = JsFormatContext;
fn fmt(&self, node: &JsNamedImportSpecifierList, f: &mut JsFormatter) -> FormatResult<()> {
let trailing_separator = FormatTrailingComma::ES5.trailing_separator(f.options());
f.join_with(&soft_line_break_or_space())
.entries(
node.format_separated(",")
.with_trailing_separator(trailing_separator),
)
.finish()
}
}
| 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/lists/variable_declarator_list.rs | crates/rome_js_formatter/src/js/lists/variable_declarator_list.rs | use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::{JsSyntaxKind, JsVariableDeclaratorList};
use rome_rowan::AstSeparatedList;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsVariableDeclaratorList;
impl FormatRule<JsVariableDeclaratorList> for FormatJsVariableDeclaratorList {
type Context = JsFormatContext;
fn fmt(&self, node: &JsVariableDeclaratorList, f: &mut JsFormatter) -> FormatResult<()> {
let length = node.len();
let is_parent_for_loop = node.syntax().grand_parent().map_or(false, |grand_parent| {
matches!(
grand_parent.kind(),
JsSyntaxKind::JS_FOR_STATEMENT
| JsSyntaxKind::JS_FOR_OF_STATEMENT
| JsSyntaxKind::JS_FOR_IN_STATEMENT
)
});
let has_any_initializer = node.iter().any(|declarator| {
declarator.map_or(false, |declarator| declarator.initializer().is_some())
});
let format_separator = format_with(|f| {
if !is_parent_for_loop && has_any_initializer {
write!(f, [hard_line_break()])
} else {
write!(f, [soft_line_break_or_space()])
}
});
let mut declarators = node.iter().zip(
node.format_separated(",")
.with_trailing_separator(TrailingSeparator::Disallowed),
);
let (first_declarator, format_first_declarator) = match declarators.next() {
Some((syntax, format_first_declarator)) => (syntax?, format_first_declarator),
None => return Err(FormatError::SyntaxError),
};
if length == 1 && !f.comments().has_leading_comments(first_declarator.syntax()) {
return write!(f, [format_first_declarator]);
}
write!(
f,
[indent(&format_once(|f| {
write!(f, [format_first_declarator])?;
if length > 1 {
write!(f, [format_separator])?;
}
f.join_with(&format_separator)
.entries(declarators.map(|(_, format)| format))
.finish()
}))]
)
}
}
| 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/lists/switch_case_list.rs | crates/rome_js_formatter/src/js/lists/switch_case_list.rs | use crate::prelude::*;
use rome_js_syntax::JsSwitchCaseList;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsSwitchCaseList;
impl FormatRule<JsSwitchCaseList> for FormatJsSwitchCaseList {
type Context = JsFormatContext;
fn fmt(&self, node: &JsSwitchCaseList, f: &mut JsFormatter) -> FormatResult<()> {
let mut join = f.join_nodes_with_hardline();
for case in node {
join.entry(case.syntax(), &format_or_verbatim(case.format()));
}
join.finish()
}
}
| 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/lists/template_element_list.rs | crates/rome_js_formatter/src/js/lists/template_element_list.rs | use crate::context::TabWidth;
use crate::js::auxiliary::template_chunk_element::AnyTemplateChunkElement;
use crate::js::auxiliary::template_element::{AnyTemplateElement, TemplateElementOptions};
use crate::prelude::*;
use crate::utils::test_each_template::EachTemplateTable;
use rome_formatter::FormatRuleWithOptions;
use rome_js_syntax::{
AnyJsExpression, AnyJsLiteralExpression, AnyJsTemplateElement, AnyTsTemplateElement,
JsLanguage, JsTemplateElementList, TsTemplateElementList,
};
use rome_rowan::{declare_node_union, AstNodeListIterator, SyntaxResult};
use std::iter::FusedIterator;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsTemplateElementList {
options: FormatJsTemplateElementListOptions,
}
impl FormatRuleWithOptions<JsTemplateElementList> for FormatJsTemplateElementList {
type Options = FormatJsTemplateElementListOptions;
fn with_options(mut self, options: Self::Options) -> Self {
self.options = options;
self
}
}
impl FormatRule<JsTemplateElementList> for FormatJsTemplateElementList {
type Context = JsFormatContext;
fn fmt(&self, node: &JsTemplateElementList, f: &mut JsFormatter) -> FormatResult<()> {
if self.options.is_test_each_pattern {
EachTemplateTable::from(node, f)?.fmt(f)
} else {
AnyTemplateElementList::JsTemplateElementList(node.clone()).fmt(f)
}
}
}
#[derive(Debug, Copy, Clone, Default)]
pub(crate) struct FormatJsTemplateElementListOptions {
pub(crate) is_test_each_pattern: bool,
}
pub(crate) enum AnyTemplateElementList {
JsTemplateElementList(JsTemplateElementList),
TsTemplateElementList(TsTemplateElementList),
}
impl Format<JsFormatContext> for AnyTemplateElementList {
fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
let layout = if self.is_simple(f.comments()) {
TemplateElementLayout::SingleLine
} else {
TemplateElementLayout::Fit
};
let mut indention = TemplateElementIndention::default();
let mut after_new_line = false;
for element in self.elements() {
match element {
AnyTemplateElementOrChunk::AnyTemplateElement(element) => {
let options = TemplateElementOptions {
after_new_line,
indention,
layout,
};
match &element {
AnyTemplateElement::JsTemplateElement(element) => {
element.format().with_options(options).fmt(f)?;
}
AnyTemplateElement::TsTemplateElement(element) => {
element.format().with_options(options).fmt(f)?;
}
}
}
AnyTemplateElementOrChunk::AnyTemplateChunkElement(chunk) => {
match &chunk {
AnyTemplateChunkElement::JsTemplateChunkElement(chunk) => {
chunk.format().fmt(f)?;
}
AnyTemplateChunkElement::TsTemplateChunkElement(chunk) => {
chunk.format().fmt(f)?;
}
}
let chunk_token = chunk.template_chunk_token()?;
let chunk_text = chunk_token.text();
let tab_width = f.options().tab_width();
indention =
TemplateElementIndention::after_last_new_line(chunk_text, tab_width);
after_new_line = chunk_text.ends_with('\n');
}
}
}
Ok(())
}
}
impl AnyTemplateElementList {
/// Returns `true` for `JsTemplate` if all elements are simple expressions that should be printed on a single line.
///
/// Simple expressions are:
/// * Identifiers: `this`, `a`
/// * Members: `a.b`, `a[b]`, `a.b[c].d`, `a.b[5]`, `a.b["test"]`
fn is_simple(&self, comments: &JsComments) -> bool {
match self {
AnyTemplateElementList::JsTemplateElementList(list) => {
if list.is_empty() {
return false;
}
let mut expression_elements = list.iter().filter_map(|element| match element {
AnyJsTemplateElement::JsTemplateElement(element) => Some(element),
_ => None,
});
expression_elements.all(|expression_element| {
match expression_element.expression() {
Ok(expression) => {
is_simple_member_expression(expression, comments).unwrap_or(false)
}
Err(_) => false,
}
})
}
AnyTemplateElementList::TsTemplateElementList(_) => false,
}
}
fn elements(&self) -> TemplateElementIterator {
match self {
AnyTemplateElementList::JsTemplateElementList(list) => {
TemplateElementIterator::JsTemplateElementList(list.iter())
}
AnyTemplateElementList::TsTemplateElementList(list) => {
TemplateElementIterator::TsTemplateElementList(list.iter())
}
}
}
}
#[derive(Debug, Copy, Clone, Default)]
pub enum TemplateElementLayout {
/// Applied when all expressions are identifiers, `this`, static member expressions, or computed member expressions with number or string literals.
/// Formats the expressions on a single line, even if their width otherwise would exceed the print width.
SingleLine,
/// Tries to format the expression on a single line but may break the expression if the line otherwise exceeds the print width.
#[default]
Fit,
}
declare_node_union! {
AnyTemplateElementOrChunk = AnyTemplateElement | AnyTemplateChunkElement
}
fn is_simple_member_expression(
expression: AnyJsExpression,
comments: &JsComments,
) -> SyntaxResult<bool> {
let mut current = expression;
loop {
if comments.has_comments(current.syntax()) {
return Ok(false);
}
current = match current {
AnyJsExpression::JsStaticMemberExpression(expression) => expression.object()?,
AnyJsExpression::JsComputedMemberExpression(expression) => {
if matches!(
expression.member()?,
AnyJsExpression::AnyJsLiteralExpression(
AnyJsLiteralExpression::JsStringLiteralExpression(_)
| AnyJsLiteralExpression::JsNumberLiteralExpression(_)
) | AnyJsExpression::JsIdentifierExpression(_)
) {
expression.object()?
} else {
break;
}
}
AnyJsExpression::JsIdentifierExpression(_) | AnyJsExpression::JsThisExpression(_) => {
return Ok(true);
}
_ => {
break;
}
}
}
Ok(false)
}
enum TemplateElementIterator {
JsTemplateElementList(AstNodeListIterator<JsLanguage, AnyJsTemplateElement>),
TsTemplateElementList(AstNodeListIterator<JsLanguage, AnyTsTemplateElement>),
}
impl Iterator for TemplateElementIterator {
type Item = AnyTemplateElementOrChunk;
fn next(&mut self) -> Option<Self::Item> {
match self {
TemplateElementIterator::JsTemplateElementList(inner) => {
let result = match inner.next()? {
AnyJsTemplateElement::JsTemplateChunkElement(chunk) => {
AnyTemplateElementOrChunk::from(AnyTemplateChunkElement::from(chunk))
}
AnyJsTemplateElement::JsTemplateElement(element) => {
AnyTemplateElementOrChunk::from(AnyTemplateElement::from(element))
}
};
Some(result)
}
TemplateElementIterator::TsTemplateElementList(inner) => {
let result = match inner.next()? {
AnyTsTemplateElement::TsTemplateChunkElement(chunk) => {
AnyTemplateElementOrChunk::from(AnyTemplateChunkElement::from(chunk))
}
AnyTsTemplateElement::TsTemplateElement(element) => {
AnyTemplateElementOrChunk::from(AnyTemplateElement::from(element))
}
};
Some(result)
}
}
}
}
impl ExactSizeIterator for TemplateElementIterator {
fn len(&self) -> usize {
match self {
TemplateElementIterator::JsTemplateElementList(inner) => inner.len(),
TemplateElementIterator::TsTemplateElementList(inner) => inner.len(),
}
}
}
impl FusedIterator for TemplateElementIterator {}
/// The indention derived from a position in the source document. Consists of indention level and spaces
#[derive(Debug, Copy, Clone, Default)]
pub struct TemplateElementIndention(u32);
impl TemplateElementIndention {
/// Returns the indention level
pub(crate) fn level(&self, tab_width: TabWidth) -> u32 {
self.0 / (u8::from(tab_width) as u32)
}
/// Returns the number of space indents on top of the indent level
pub(crate) fn align(&self, tab_width: TabWidth) -> u8 {
(self.0 % u8::from(tab_width) as u32) as u8
}
/// Computes the indention after the last new line character.
fn after_last_new_line(text: &str, tab_width: TabWidth) -> Self {
let by_new_line = text.rsplit_once('\n');
let size = match by_new_line {
None => 0,
Some((_, after_new_line)) => {
let tab_width: u32 = u8::from(tab_width).into();
let mut size: u32 = 0;
for c in after_new_line.chars() {
match c {
'\t' => {
// Tabs behave in a way that they are aligned to the nearest
// multiple of tab_width:
// number of spaces -> added size
// 0 -> 4, 1 -> 4, 2 -> 4, 3 -> 4
// 4 -> 8, 5 -> 8, 6 -> 8, 7 -> 8 ..
// Or in other words, it clips the size to the next multiple of tab width.
size = size + tab_width - (size % tab_width);
}
' ' => {
size += 1;
}
_ => break,
};
}
size
}
};
TemplateElementIndention(size)
}
}
| 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/lists/method_modifier_list.rs | crates/rome_js_formatter/src/js/lists/method_modifier_list.rs | use crate::prelude::*;
use crate::utils::format_modifiers::FormatModifiers;
use rome_js_syntax::JsMethodModifierList;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsMethodModifierList;
impl FormatRule<JsMethodModifierList> for FormatJsMethodModifierList {
type Context = JsFormatContext;
fn fmt(&self, node: &JsMethodModifierList, f: &mut JsFormatter) -> FormatResult<()> {
FormatModifiers::from(node.clone()).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/assignments/identifier_assignment.rs | crates/rome_js_formatter/src/js/assignments/identifier_assignment.rs | use crate::prelude::*;
use rome_formatter::write;
use crate::parentheses::NeedsParentheses;
use rome_js_syntax::{JsForOfStatement, JsIdentifierAssignmentFields};
use rome_js_syntax::{JsIdentifierAssignment, JsSyntaxNode};
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsIdentifierAssignment;
impl FormatNodeRule<JsIdentifierAssignment> for FormatJsIdentifierAssignment {
fn fmt_fields(&self, node: &JsIdentifierAssignment, f: &mut JsFormatter) -> FormatResult<()> {
let JsIdentifierAssignmentFields { name_token } = node.as_fields();
write![f, [name_token.format()]]
}
fn needs_parentheses(&self, item: &JsIdentifierAssignment) -> bool {
item.needs_parentheses()
}
}
impl NeedsParentheses for JsIdentifierAssignment {
#[inline]
fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool {
let is_async = self
.name_token()
.map_or(false, |name| name.text_trimmed() == "async");
if is_async && JsForOfStatement::can_cast(parent.kind()) {
let for_of = JsForOfStatement::unwrap_cast(parent.clone());
for_of.await_token().is_none()
} else {
false
}
}
}
#[cfg(test)]
mod tests {
use crate::{assert_needs_parentheses, assert_not_needs_parentheses};
use rome_js_syntax::JsIdentifierAssignment;
#[test]
fn needs_parentheses() {
assert_needs_parentheses!("for ((async) of []) {}", JsIdentifierAssignment);
assert_not_needs_parentheses!("for await (async of []) {}", JsIdentifierAssignment);
assert_not_needs_parentheses!("for (test of []) {}", JsIdentifierAssignment);
}
}
| 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/assignments/assignment_with_default.rs | crates/rome_js_formatter/src/js/assignments/assignment_with_default.rs | use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::JsAssignmentWithDefault;
use rome_js_syntax::JsAssignmentWithDefaultFields;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsAssignmentWithDefault;
impl FormatNodeRule<JsAssignmentWithDefault> for FormatJsAssignmentWithDefault {
fn fmt_fields(&self, node: &JsAssignmentWithDefault, f: &mut JsFormatter) -> FormatResult<()> {
let JsAssignmentWithDefaultFields {
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/assignments/object_assignment_pattern_rest.rs | crates/rome_js_formatter/src/js/assignments/object_assignment_pattern_rest.rs | use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::JsObjectAssignmentPatternRest;
use rome_js_syntax::JsObjectAssignmentPatternRestFields;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsObjectAssignmentPatternRest;
impl FormatNodeRule<JsObjectAssignmentPatternRest> for FormatJsObjectAssignmentPatternRest {
fn fmt_fields(
&self,
node: &JsObjectAssignmentPatternRest,
f: &mut JsFormatter,
) -> FormatResult<()> {
let JsObjectAssignmentPatternRestFields {
dotdotdot_token,
target,
} = node.as_fields();
write!(f, [dotdotdot_token.format(), target.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/assignments/static_member_assignment.rs | crates/rome_js_formatter/src/js/assignments/static_member_assignment.rs | use crate::js::expressions::static_member_expression::AnyJsStaticMemberLike;
use crate::parentheses::NeedsParentheses;
use crate::prelude::*;
use rome_js_syntax::{JsStaticMemberAssignment, JsSyntaxNode};
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsStaticMemberAssignment;
impl FormatNodeRule<JsStaticMemberAssignment> for FormatJsStaticMemberAssignment {
fn fmt_fields(&self, node: &JsStaticMemberAssignment, f: &mut JsFormatter) -> FormatResult<()> {
AnyJsStaticMemberLike::from(node.clone()).fmt(f)
}
fn needs_parentheses(&self, item: &JsStaticMemberAssignment) -> bool {
item.needs_parentheses()
}
}
impl NeedsParentheses for JsStaticMemberAssignment {
#[inline]
fn needs_parentheses(&self) -> bool {
false
}
#[inline]
fn needs_parentheses_with_parent(&self, _: &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/assignments/object_assignment_pattern_shorthand_property.rs | crates/rome_js_formatter/src/js/assignments/object_assignment_pattern_shorthand_property.rs | use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::JsObjectAssignmentPatternShorthandProperty;
use rome_js_syntax::JsObjectAssignmentPatternShorthandPropertyFields;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsObjectAssignmentPatternShorthandProperty;
impl FormatNodeRule<JsObjectAssignmentPatternShorthandProperty>
for FormatJsObjectAssignmentPatternShorthandProperty
{
fn fmt_fields(
&self,
node: &JsObjectAssignmentPatternShorthandProperty,
f: &mut JsFormatter,
) -> FormatResult<()> {
let JsObjectAssignmentPatternShorthandPropertyFields { 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/assignments/computed_member_assignment.rs | crates/rome_js_formatter/src/js/assignments/computed_member_assignment.rs | use crate::prelude::*;
use crate::parentheses::NeedsParentheses;
use rome_js_syntax::{AnyJsComputedMember, JsComputedMemberAssignment, JsSyntaxNode};
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsComputedMemberAssignment;
impl FormatNodeRule<JsComputedMemberAssignment> for FormatJsComputedMemberAssignment {
fn fmt_fields(
&self,
node: &JsComputedMemberAssignment,
f: &mut JsFormatter,
) -> FormatResult<()> {
AnyJsComputedMember::from(node.clone()).fmt(f)
}
fn needs_parentheses(&self, item: &JsComputedMemberAssignment) -> bool {
item.needs_parentheses()
}
}
impl NeedsParentheses for JsComputedMemberAssignment {
#[inline]
fn needs_parentheses(&self) -> bool {
false
}
#[inline]
fn needs_parentheses_with_parent(&self, _: &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/assignments/object_assignment_pattern_property.rs | crates/rome_js_formatter/src/js/assignments/object_assignment_pattern_property.rs | use crate::prelude::*;
use crate::utils::AnyJsAssignmentLike;
use rome_formatter::write;
use rome_js_syntax::JsObjectAssignmentPatternProperty;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsObjectAssignmentPatternProperty;
impl FormatNodeRule<JsObjectAssignmentPatternProperty> for FormatJsObjectAssignmentPatternProperty {
fn fmt_fields(
&self,
node: &JsObjectAssignmentPatternProperty,
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/assignments/parenthesized_assignment.rs | crates/rome_js_formatter/src/js/assignments/parenthesized_assignment.rs | use crate::parentheses::NeedsParentheses;
use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::JsParenthesizedAssignment;
use rome_js_syntax::{JsParenthesizedAssignmentFields, JsSyntaxNode};
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsParenthesizedAssignment;
impl FormatNodeRule<JsParenthesizedAssignment> for FormatJsParenthesizedAssignment {
fn fmt_fields(
&self,
node: &JsParenthesizedAssignment,
f: &mut JsFormatter,
) -> FormatResult<()> {
let JsParenthesizedAssignmentFields {
l_paren_token,
assignment,
r_paren_token,
} = node.as_fields();
write![
f,
[
l_paren_token.format(),
assignment.format(),
r_paren_token.format(),
]
]
}
fn needs_parentheses(&self, item: &JsParenthesizedAssignment) -> bool {
item.needs_parentheses()
}
}
impl NeedsParentheses for JsParenthesizedAssignment {
#[inline]
fn needs_parentheses(&self) -> bool {
false
}
#[inline]
fn needs_parentheses_with_parent(&self, _: &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/assignments/mod.rs | crates/rome_js_formatter/src/js/assignments/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_assignment_pattern;
pub(crate) mod array_assignment_pattern_rest_element;
pub(crate) mod assignment_with_default;
pub(crate) mod computed_member_assignment;
pub(crate) mod identifier_assignment;
pub(crate) mod object_assignment_pattern;
pub(crate) mod object_assignment_pattern_property;
pub(crate) mod object_assignment_pattern_rest;
pub(crate) mod object_assignment_pattern_shorthand_property;
pub(crate) mod parenthesized_assignment;
pub(crate) mod static_member_assignment;
| 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/assignments/array_assignment_pattern_rest_element.rs | crates/rome_js_formatter/src/js/assignments/array_assignment_pattern_rest_element.rs | use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::JsArrayAssignmentPatternRestElement;
use rome_js_syntax::JsArrayAssignmentPatternRestElementFields;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsArrayAssignmentPatternRestElement;
impl FormatNodeRule<JsArrayAssignmentPatternRestElement>
for FormatJsArrayAssignmentPatternRestElement
{
fn fmt_fields(
&self,
node: &JsArrayAssignmentPatternRestElement,
f: &mut JsFormatter,
) -> FormatResult<()> {
let JsArrayAssignmentPatternRestElementFields {
dotdotdot_token,
pattern,
} = node.as_fields();
write!(f, [dotdotdot_token.format(), pattern.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/assignments/object_assignment_pattern.rs | crates/rome_js_formatter/src/js/assignments/object_assignment_pattern.rs | use crate::parentheses::NeedsParentheses;
use crate::prelude::*;
use crate::utils::JsObjectPatternLike;
use rome_formatter::write;
use rome_js_syntax::{JsObjectAssignmentPattern, JsSyntaxNode};
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsObjectAssignmentPattern;
impl FormatNodeRule<JsObjectAssignmentPattern> for FormatJsObjectAssignmentPattern {
fn fmt_fields(
&self,
node: &JsObjectAssignmentPattern,
f: &mut JsFormatter,
) -> FormatResult<()> {
write!(f, [JsObjectPatternLike::from(node.clone())])
}
fn needs_parentheses(&self, item: &JsObjectAssignmentPattern) -> bool {
item.needs_parentheses()
}
fn fmt_dangling_comments(
&self,
_: &JsObjectAssignmentPattern,
_: &mut JsFormatter,
) -> FormatResult<()> {
// Handled inside of `JsObjectPatternLike`
Ok(())
}
}
impl NeedsParentheses for JsObjectAssignmentPattern {
#[inline]
fn needs_parentheses(&self) -> bool {
false
}
#[inline]
fn needs_parentheses_with_parent(&self, _: &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/assignments/array_assignment_pattern.rs | crates/rome_js_formatter/src/js/assignments/array_assignment_pattern.rs | use crate::parentheses::NeedsParentheses;
use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::JsArrayAssignmentPattern;
use rome_js_syntax::{JsArrayAssignmentPatternFields, JsSyntaxNode};
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsArrayAssignmentPattern;
impl FormatNodeRule<JsArrayAssignmentPattern> for FormatJsArrayAssignmentPattern {
fn fmt_fields(&self, node: &JsArrayAssignmentPattern, f: &mut JsFormatter) -> FormatResult<()> {
let JsArrayAssignmentPatternFields {
l_brack_token,
elements,
r_brack_token,
} = node.as_fields();
write!(f, [l_brack_token.format(),])?;
if elements.is_empty() {
write!(
f,
[format_dangling_comments(node.syntax()).with_block_indent()]
)?;
} else {
write!(f, [group(&soft_block_indent(&elements.format()))])?;
}
write!(f, [r_brack_token.format()])
}
fn needs_parentheses(&self, item: &JsArrayAssignmentPattern) -> bool {
item.needs_parentheses()
}
fn fmt_dangling_comments(
&self,
_: &JsArrayAssignmentPattern,
_: &mut JsFormatter,
) -> FormatResult<()> {
// Handled inside of `fmt_fields`
Ok(())
}
}
impl NeedsParentheses for JsArrayAssignmentPattern {
#[inline]
fn needs_parentheses(&self) -> bool {
false
}
#[inline]
fn needs_parentheses_with_parent(&self, _: &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/bogus/bogus_parameter.rs | crates/rome_js_formatter/src/js/bogus/bogus_parameter.rs | use crate::FormatBogusNodeRule;
use rome_js_syntax::JsBogusParameter;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsBogusParameter;
impl FormatBogusNodeRule<JsBogusParameter> for FormatJsBogusParameter {}
| 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/bogus/bogus_assignment.rs | crates/rome_js_formatter/src/js/bogus/bogus_assignment.rs | use crate::parentheses::NeedsParentheses;
use crate::FormatBogusNodeRule;
use rome_js_syntax::{JsBogusAssignment, JsSyntaxNode};
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsBogusAssignment;
impl FormatBogusNodeRule<JsBogusAssignment> for FormatJsBogusAssignment {}
impl NeedsParentheses for JsBogusAssignment {
#[inline]
fn needs_parentheses(&self) -> bool {
false
}
#[inline]
fn needs_parentheses_with_parent(&self, _: &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/bogus/bogus_import_assertion_entry.rs | crates/rome_js_formatter/src/js/bogus/bogus_import_assertion_entry.rs | use crate::FormatBogusNodeRule;
use rome_js_syntax::JsBogusImportAssertionEntry;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsBogusImportAssertionEntry;
impl FormatBogusNodeRule<JsBogusImportAssertionEntry> for FormatJsBogusImportAssertionEntry {}
| 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/bogus/bogus_statement.rs | crates/rome_js_formatter/src/js/bogus/bogus_statement.rs | use crate::FormatBogusNodeRule;
use rome_js_syntax::JsBogusStatement;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsBogusStatement;
impl FormatBogusNodeRule<JsBogusStatement> for FormatJsBogusStatement {}
| 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/bogus/bogus_expression.rs | crates/rome_js_formatter/src/js/bogus/bogus_expression.rs | use crate::parentheses::NeedsParentheses;
use crate::FormatBogusNodeRule;
use rome_js_syntax::{JsBogusExpression, JsSyntaxNode};
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsBogusExpression;
impl FormatBogusNodeRule<JsBogusExpression> for FormatJsBogusExpression {}
impl NeedsParentheses for JsBogusExpression {
#[inline]
fn needs_parentheses(&self) -> bool {
false
}
#[inline]
fn needs_parentheses_with_parent(&self, _parent: &JsSyntaxNode) -> bool {
self.needs_parentheses()
}
}
| 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/bogus/mod.rs | crates/rome_js_formatter/src/js/bogus/mod.rs | //! This is a generated file. Don't modify it by hand! Run 'cargo codegen formatter' to re-generate the file.
#[allow(clippy::module_inception)]
pub(crate) mod bogus;
pub(crate) mod bogus_assignment;
pub(crate) mod bogus_binding;
pub(crate) mod bogus_expression;
pub(crate) mod bogus_import_assertion_entry;
pub(crate) mod bogus_member;
pub(crate) mod bogus_named_import_specifier;
pub(crate) mod bogus_parameter;
pub(crate) mod bogus_statement;
| 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/bogus/bogus.rs | crates/rome_js_formatter/src/js/bogus/bogus.rs | use crate::FormatBogusNodeRule;
use rome_js_syntax::JsBogus;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsBogus;
impl FormatBogusNodeRule<JsBogus> for FormatJsBogus {}
| 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/bogus/bogus_named_import_specifier.rs | crates/rome_js_formatter/src/js/bogus/bogus_named_import_specifier.rs | use crate::FormatBogusNodeRule;
use rome_js_syntax::JsBogusNamedImportSpecifier;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsBogusNamedImportSpecifier;
impl FormatBogusNodeRule<JsBogusNamedImportSpecifier> for FormatJsBogusNamedImportSpecifier {}
| 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/bogus/bogus_binding.rs | crates/rome_js_formatter/src/js/bogus/bogus_binding.rs | use crate::FormatBogusNodeRule;
use rome_js_syntax::JsBogusBinding;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsBogusBinding;
impl FormatBogusNodeRule<JsBogusBinding> for FormatJsBogusBinding {}
| 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/bogus/bogus_member.rs | crates/rome_js_formatter/src/js/bogus/bogus_member.rs | use crate::FormatBogusNodeRule;
use rome_js_syntax::JsBogusMember;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsBogusMember;
impl FormatBogusNodeRule<JsBogusMember> for FormatJsBogusMember {}
| 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/declarations/variable_declaration.rs | crates/rome_js_formatter/src/js/declarations/variable_declaration.rs | use crate::prelude::*;
use rome_formatter::{format_args, write};
use rome_js_syntax::JsVariableDeclaration;
use rome_js_syntax::JsVariableDeclarationFields;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsVariableDeclaration;
impl FormatNodeRule<JsVariableDeclaration> for FormatJsVariableDeclaration {
fn fmt_fields(&self, node: &JsVariableDeclaration, f: &mut JsFormatter) -> FormatResult<()> {
let JsVariableDeclarationFields {
await_token,
kind,
declarators,
} = node.as_fields();
if let Some(await_token) = await_token {
write!(f, [await_token.format(), space()])?;
}
write![
f,
[group(&format_args![
kind.format(),
space(),
declarators.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/declarations/for_variable_declaration.rs | crates/rome_js_formatter/src/js/declarations/for_variable_declaration.rs | use crate::prelude::*;
use rome_formatter::{format_args, write};
use rome_js_syntax::JsForVariableDeclaration;
use rome_js_syntax::JsForVariableDeclarationFields;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsForVariableDeclaration;
impl FormatNodeRule<JsForVariableDeclaration> for FormatJsForVariableDeclaration {
fn fmt_fields(&self, node: &JsForVariableDeclaration, f: &mut JsFormatter) -> FormatResult<()> {
let JsForVariableDeclarationFields {
await_token,
kind_token,
declarator,
} = node.as_fields();
if let Some(await_token) = await_token {
write!(f, [await_token.format(), space()])?;
}
write![
f,
[group(&format_args![
kind_token.format(),
space(),
declarator.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/declarations/function_declaration.rs | crates/rome_js_formatter/src/js/declarations/function_declaration.rs | use crate::prelude::*;
use crate::js::expressions::call_arguments::GroupedCallArgumentLayout;
use crate::utils::function_body::{FormatMaybeCachedFunctionBody, FunctionBodyCacheMode};
use rome_formatter::{write, RemoveSoftLinesBuffer};
use rome_js_syntax::{
AnyJsBinding, AnyTsReturnType, AnyTsType, JsFunctionBody, JsFunctionDeclaration,
JsFunctionExportDefaultDeclaration, JsFunctionExpression, JsParameters, JsSyntaxToken,
TsDeclareFunctionDeclaration, TsDeclareFunctionExportDefaultDeclaration,
TsReturnTypeAnnotation, TsTypeParameters,
};
use rome_rowan::{declare_node_union, SyntaxResult};
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsFunctionDeclaration;
impl FormatNodeRule<JsFunctionDeclaration> for FormatJsFunctionDeclaration {
fn fmt_fields(&self, node: &JsFunctionDeclaration, f: &mut JsFormatter) -> FormatResult<()> {
write![f, [FormatFunction::from(node.clone())]]
}
}
declare_node_union! {
pub(crate) FormatFunction =
JsFunctionDeclaration |
JsFunctionExpression |
JsFunctionExportDefaultDeclaration |
TsDeclareFunctionDeclaration |
TsDeclareFunctionExportDefaultDeclaration
}
#[derive(Copy, Clone, Debug, Default)]
pub(crate) struct FormatFunctionOptions {
pub call_argument_layout: Option<GroupedCallArgumentLayout>,
pub body_cache_mode: FunctionBodyCacheMode,
}
impl FormatFunction {
fn async_token(&self) -> Option<JsSyntaxToken> {
match self {
FormatFunction::JsFunctionDeclaration(declaration) => declaration.async_token(),
FormatFunction::JsFunctionExpression(expression) => expression.async_token(),
FormatFunction::JsFunctionExportDefaultDeclaration(declaration) => {
declaration.async_token()
}
FormatFunction::TsDeclareFunctionDeclaration(member) => member.async_token(),
FormatFunction::TsDeclareFunctionExportDefaultDeclaration(member) => {
member.async_token()
}
}
}
fn function_token(&self) -> SyntaxResult<JsSyntaxToken> {
match self {
FormatFunction::JsFunctionDeclaration(declaration) => declaration.function_token(),
FormatFunction::JsFunctionExpression(expression) => expression.function_token(),
FormatFunction::JsFunctionExportDefaultDeclaration(declaration) => {
declaration.function_token()
}
FormatFunction::TsDeclareFunctionDeclaration(declaration) => {
declaration.function_token()
}
FormatFunction::TsDeclareFunctionExportDefaultDeclaration(declaration) => {
declaration.function_token()
}
}
}
fn star_token(&self) -> Option<JsSyntaxToken> {
match self {
FormatFunction::JsFunctionDeclaration(declaration) => declaration.star_token(),
FormatFunction::JsFunctionExpression(expression) => expression.star_token(),
FormatFunction::JsFunctionExportDefaultDeclaration(declaration) => {
declaration.star_token()
}
FormatFunction::TsDeclareFunctionDeclaration(_) => None,
FormatFunction::TsDeclareFunctionExportDefaultDeclaration(_) => None,
}
}
fn id(&self) -> SyntaxResult<Option<AnyJsBinding>> {
match self {
FormatFunction::JsFunctionDeclaration(declaration) => declaration.id().map(Some),
FormatFunction::JsFunctionExpression(expression) => Ok(expression.id()),
FormatFunction::JsFunctionExportDefaultDeclaration(declaration) => Ok(declaration.id()),
FormatFunction::TsDeclareFunctionDeclaration(declaration) => declaration.id().map(Some),
FormatFunction::TsDeclareFunctionExportDefaultDeclaration(declaration) => {
Ok(declaration.id())
}
}
}
fn type_parameters(&self) -> Option<TsTypeParameters> {
match self {
FormatFunction::JsFunctionDeclaration(declaration) => declaration.type_parameters(),
FormatFunction::JsFunctionExpression(expression) => expression.type_parameters(),
FormatFunction::JsFunctionExportDefaultDeclaration(declaration) => {
declaration.type_parameters()
}
FormatFunction::TsDeclareFunctionDeclaration(declaration) => {
declaration.type_parameters()
}
FormatFunction::TsDeclareFunctionExportDefaultDeclaration(declaration) => {
declaration.type_parameters()
}
}
}
fn parameters(&self) -> SyntaxResult<JsParameters> {
match self {
FormatFunction::JsFunctionDeclaration(declaration) => declaration.parameters(),
FormatFunction::JsFunctionExpression(expression) => expression.parameters(),
FormatFunction::JsFunctionExportDefaultDeclaration(declaration) => {
declaration.parameters()
}
FormatFunction::TsDeclareFunctionDeclaration(declaration) => declaration.parameters(),
FormatFunction::TsDeclareFunctionExportDefaultDeclaration(declaration) => {
declaration.parameters()
}
}
}
fn return_type_annotation(&self) -> Option<TsReturnTypeAnnotation> {
match self {
FormatFunction::JsFunctionDeclaration(declaration) => {
declaration.return_type_annotation()
}
FormatFunction::JsFunctionExpression(expression) => expression.return_type_annotation(),
FormatFunction::JsFunctionExportDefaultDeclaration(declaration) => {
declaration.return_type_annotation()
}
FormatFunction::TsDeclareFunctionDeclaration(declaration) => {
declaration.return_type_annotation()
}
FormatFunction::TsDeclareFunctionExportDefaultDeclaration(declaration) => {
declaration.return_type_annotation()
}
}
}
fn body(&self) -> SyntaxResult<Option<JsFunctionBody>> {
Ok(match self {
FormatFunction::JsFunctionDeclaration(declaration) => Some(declaration.body()?),
FormatFunction::JsFunctionExpression(expression) => Some(expression.body()?),
FormatFunction::JsFunctionExportDefaultDeclaration(declaration) => {
Some(declaration.body()?)
}
FormatFunction::TsDeclareFunctionDeclaration(_) => None,
FormatFunction::TsDeclareFunctionExportDefaultDeclaration(_) => None,
})
}
/// Formats the function with the specified `options`.
///
/// # Errors
///
/// Returns [`FormatError::PoorLayout`] if [`call_argument_layout`](FormatFunctionOptions::call_argument_layout] is `Some`
/// and the function parameters contain some content that [*force a group to break*](FormatElements::will_break).
///
/// This error is handled by [FormatJsCallArguments].
pub(crate) fn fmt_with_options(
&self,
f: &mut JsFormatter,
options: &FormatFunctionOptions,
) -> FormatResult<()> {
if let Some(async_token) = self.async_token() {
write!(f, [async_token.format(), space()])?;
}
write!(
f,
[self.function_token().format(), self.star_token().format()]
)?;
match self.id()? {
Some(id) => {
write!(f, [space(), id.format()])?;
}
None => {
write!(f, [space()])?;
}
}
let type_parameters = self.type_parameters();
let parameters = self.parameters()?;
let return_type_annotation = self.return_type_annotation();
write!(f, [type_parameters.format()])?;
let format_parameters = format_with(|f: &mut JsFormatter| {
if options.call_argument_layout.is_some() {
let mut buffer = RemoveSoftLinesBuffer::new(f);
let mut recording = buffer.start_recording();
write!(recording, [parameters.format()])?;
let recorded = recording.stop();
if recorded.will_break() {
return Err(FormatError::PoorLayout);
}
} else {
parameters.format().fmt(f)?;
}
Ok(())
});
write!(
f,
[group(&format_with(|f| {
let mut format_return_type_annotation = return_type_annotation.format().memoized();
let group_parameters = should_group_function_parameters(
type_parameters.as_ref(),
parameters.items().len(),
return_type_annotation
.as_ref()
.map(|annotation| annotation.ty()),
&mut format_return_type_annotation,
f,
)?;
if group_parameters {
write!(f, [group(&format_parameters)])?;
} else {
write!(f, [format_parameters])?;
}
write!(f, [format_return_type_annotation])
}))]
)?;
if let Some(body) = self.body()? {
write!(
f,
[
space(),
FormatMaybeCachedFunctionBody {
body: &body.into(),
mode: options.body_cache_mode
}
]
)?;
}
Ok(())
}
}
impl Format<JsFormatContext> for FormatFunction {
fn fmt(&self, f: &mut JsFormatter) -> FormatResult<()> {
self.fmt_with_options(f, &FormatFunctionOptions::default())?;
Ok(())
}
}
/// Returns `true` if the function parameters should be grouped.
/// Grouping the parameters has the effect that the return type will break first.
pub(crate) fn should_group_function_parameters(
type_parameters: Option<&TsTypeParameters>,
parameter_count: usize,
return_type: Option<SyntaxResult<AnyTsReturnType>>,
formatted_return_type: &mut Memoized<impl Format<JsFormatContext>, JsFormatContext>,
f: &mut JsFormatter,
) -> FormatResult<bool> {
let return_type = match return_type {
Some(return_type) => return_type?,
None => return Ok(false),
};
if let Some(type_parameters) = type_parameters {
match type_parameters.items().len() {
0 => {
// fall through
}
1 => {
// SAFETY: Safe because the length is 1
let first = type_parameters.items().iter().next().unwrap()?;
if first.constraint().is_none() || first.default().is_some() {
return Ok(false);
}
}
_ => return Ok(false),
}
}
let result = if parameter_count != 1 {
false
} else {
matches!(
return_type,
AnyTsReturnType::AnyTsType(AnyTsType::TsObjectType(_) | AnyTsType::TsMappedType(_))
) || formatted_return_type.inspect(f)?.will_break()
};
Ok(result)
}
| 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/declarations/class_export_default_declaration.rs | crates/rome_js_formatter/src/js/declarations/class_export_default_declaration.rs | use crate::prelude::*;
use crate::utils::format_class::FormatClass;
use rome_js_syntax::JsClassExportDefaultDeclaration;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsClassExportDefaultDeclaration;
impl FormatNodeRule<JsClassExportDefaultDeclaration> for FormatJsClassExportDefaultDeclaration {
fn fmt_fields(
&self,
node: &JsClassExportDefaultDeclaration,
f: &mut JsFormatter,
) -> FormatResult<()> {
FormatClass::from(&node.clone().into()).fmt(f)
}
fn fmt_dangling_comments(
&self,
_: &JsClassExportDefaultDeclaration,
_: &mut JsFormatter,
) -> FormatResult<()> {
/* Formatted as part of `FormatClass` */
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/declarations/function_export_default_declaration.rs | crates/rome_js_formatter/src/js/declarations/function_export_default_declaration.rs | use crate::prelude::*;
use rome_formatter::write;
use crate::js::declarations::function_declaration::FormatFunction;
use rome_js_syntax::JsFunctionExportDefaultDeclaration;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsFunctionExportDefaultDeclaration;
impl FormatNodeRule<JsFunctionExportDefaultDeclaration>
for FormatJsFunctionExportDefaultDeclaration
{
fn fmt_fields(
&self,
node: &JsFunctionExportDefaultDeclaration,
f: &mut JsFormatter,
) -> FormatResult<()> {
write![f, [FormatFunction::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/declarations/class_declaration.rs | crates/rome_js_formatter/src/js/declarations/class_declaration.rs | use crate::prelude::*;
use crate::utils::format_class::FormatClass;
use rome_js_syntax::JsClassDeclaration;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsClassDeclaration;
impl FormatNodeRule<JsClassDeclaration> for FormatJsClassDeclaration {
fn fmt_fields(&self, node: &JsClassDeclaration, f: &mut JsFormatter) -> FormatResult<()> {
FormatClass::from(&node.clone().into()).fmt(f)
}
fn fmt_dangling_comments(
&self,
_: &JsClassDeclaration,
_: &mut JsFormatter,
) -> FormatResult<()> {
// Formatted as part of `FormatClass`
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/declarations/mod.rs | crates/rome_js_formatter/src/js/declarations/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 catch_declaration;
pub(crate) mod class_declaration;
pub(crate) mod class_export_default_declaration;
pub(crate) mod for_variable_declaration;
pub(crate) mod function_declaration;
pub(crate) mod function_export_default_declaration;
pub(crate) mod variable_declaration;
| 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/declarations/catch_declaration.rs | crates/rome_js_formatter/src/js/declarations/catch_declaration.rs | use crate::prelude::*;
use rome_formatter::{format_args, write};
use rome_js_syntax::JsCatchDeclaration;
use rome_js_syntax::JsCatchDeclarationFields;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsCatchDeclaration;
impl FormatNodeRule<JsCatchDeclaration> for FormatJsCatchDeclaration {
fn fmt_fields(&self, node: &JsCatchDeclaration, f: &mut JsFormatter) -> FormatResult<()> {
let JsCatchDeclarationFields {
l_paren_token,
binding,
r_paren_token,
type_annotation,
} = node.as_fields();
let binding = binding?;
let leading_comment_with_break = f
.comments()
.leading_comments(binding.syntax())
.iter()
.any(|comment| comment.lines_after() > 0 || comment.kind().is_line());
let last_parameter_node = type_annotation
.as_ref()
.map(|type_annotation| type_annotation.syntax())
.unwrap_or_else(|| binding.syntax());
let trailing_comment_with_break = f
.comments()
.trailing_comments(last_parameter_node)
.iter()
.any(|comment| comment.lines_before() > 0 || comment.kind().is_line());
if leading_comment_with_break || trailing_comment_with_break {
write!(
f,
[
l_paren_token.format(),
soft_block_indent(&format_args![binding.format(), type_annotation.format()]),
r_paren_token.format()
]
)
} else {
write!(
f,
[
l_paren_token.format(),
binding.format(),
type_annotation.format(),
r_paren_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/object_binding_pattern_property.rs | crates/rome_js_formatter/src/js/bindings/object_binding_pattern_property.rs | use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::JsObjectBindingPatternProperty;
use rome_js_syntax::JsObjectBindingPatternPropertyFields;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsObjectBindingPatternProperty;
impl FormatNodeRule<JsObjectBindingPatternProperty> for FormatJsObjectBindingPatternProperty {
fn fmt_fields(
&self,
node: &JsObjectBindingPatternProperty,
f: &mut JsFormatter,
) -> FormatResult<()> {
let JsObjectBindingPatternPropertyFields {
member,
colon_token,
pattern,
init,
} = node.as_fields();
write![
f,
[
member.format(),
colon_token.format(),
space(),
pattern.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/bindings/parameters.rs | crates/rome_js_formatter/src/js/bindings/parameters.rs | use crate::prelude::*;
use rome_formatter::{write, CstFormatContext};
use crate::js::expressions::arrow_function_expression::can_avoid_parentheses;
use crate::js::lists::parameter_list::FormatJsAnyParameterList;
use crate::utils::test_call::is_test_call_argument;
use rome_js_syntax::parameter_ext::{AnyJsParameterList, AnyParameter};
use rome_js_syntax::{
AnyJsConstructorParameter, AnyJsFormalParameter, AnyTsType, JsArrowFunctionExpression,
JsConstructorParameters, JsParameters, JsSyntaxToken,
};
use rome_rowan::{declare_node_union, SyntaxResult};
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsParameters;
impl FormatNodeRule<JsParameters> for FormatJsParameters {
fn fmt_fields(&self, node: &JsParameters, f: &mut JsFormatter) -> FormatResult<()> {
FormatAnyJsParameters::from(node.clone()).fmt(f)
}
fn fmt_dangling_comments(&self, _: &JsParameters, _: &mut JsFormatter) -> FormatResult<()> {
// Formatted inside of `FormatJsAnyParameters
Ok(())
}
}
declare_node_union! {
pub(crate) FormatAnyJsParameters = JsParameters | JsConstructorParameters
}
impl Format<JsFormatContext> for FormatAnyJsParameters {
fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
let list = self.list();
let has_any_decorated_parameter = list.has_any_decorated_parameter();
let can_hug = should_hug_function_parameters(self, f.context().comments())?
&& !has_any_decorated_parameter;
let layout = if list.is_empty() {
ParameterLayout::NoParameters
} else if can_hug || self.is_in_test_call()? {
ParameterLayout::Hug
} else {
ParameterLayout::Default
};
let l_paren_token = self.l_paren_token()?;
let r_paren_token = self.r_paren_token()?;
let parentheses_not_needed = self
.as_arrow_function_expression()
.map_or(false, |expression| can_avoid_parentheses(&expression, f));
match layout {
ParameterLayout::NoParameters => {
write!(
f,
[
l_paren_token.format(),
format_dangling_comments(self.syntax()).with_soft_block_indent(),
r_paren_token.format()
]
)
}
ParameterLayout::Hug => {
if !parentheses_not_needed {
write!(f, [l_paren_token.format()])?;
} else {
write!(f, [format_removed(&l_paren_token)])?;
}
write!(
f,
[FormatJsAnyParameterList::with_layout(
&list,
ParameterLayout::Hug
)]
)?;
if !parentheses_not_needed {
write!(f, [&r_paren_token.format()])?;
} else {
write!(f, [format_removed(&r_paren_token)])?;
}
Ok(())
}
ParameterLayout::Default => {
if !parentheses_not_needed {
write!(f, [l_paren_token.format()])?;
} else {
write!(f, [format_removed(&l_paren_token)])?;
}
write!(
f,
[soft_block_indent(&FormatJsAnyParameterList::with_layout(
&list,
ParameterLayout::Default
))]
)?;
if !parentheses_not_needed {
write!(f, [r_paren_token.format()])?;
} else {
write!(f, [format_removed(&r_paren_token)])?;
}
Ok(())
}
}
}
}
impl FormatAnyJsParameters {
fn l_paren_token(&self) -> SyntaxResult<JsSyntaxToken> {
match self {
FormatAnyJsParameters::JsParameters(parameters) => parameters.l_paren_token(),
FormatAnyJsParameters::JsConstructorParameters(parameters) => {
parameters.l_paren_token()
}
}
}
fn list(&self) -> AnyJsParameterList {
match self {
FormatAnyJsParameters::JsParameters(parameters) => {
AnyJsParameterList::from(parameters.items())
}
FormatAnyJsParameters::JsConstructorParameters(parameters) => {
AnyJsParameterList::from(parameters.parameters())
}
}
}
fn r_paren_token(&self) -> SyntaxResult<JsSyntaxToken> {
match self {
FormatAnyJsParameters::JsParameters(parameters) => parameters.r_paren_token(),
FormatAnyJsParameters::JsConstructorParameters(parameters) => {
parameters.r_paren_token()
}
}
}
/// Returns `true` for function parameters if the function is an argument of a [test `CallExpression`](is_test_call_expression).
fn is_in_test_call(&self) -> SyntaxResult<bool> {
let result = match self {
FormatAnyJsParameters::JsParameters(parameters) => match parameters.syntax().parent() {
Some(function) => is_test_call_argument(&function)?,
None => false,
},
FormatAnyJsParameters::JsConstructorParameters(_) => false,
};
Ok(result)
}
fn as_arrow_function_expression(&self) -> Option<JsArrowFunctionExpression> {
match self {
FormatAnyJsParameters::JsParameters(parameters) => parameters
.syntax()
.parent()
.and_then(JsArrowFunctionExpression::cast),
FormatAnyJsParameters::JsConstructorParameters(_) => None,
}
}
}
#[derive(Copy, Debug, Clone, Eq, PartialEq)]
pub enum ParameterLayout {
/// ```javascript
/// function test() {}
/// ```
NoParameters,
/// Enforce that the opening and closing parentheses aren't separated from the first token of the parameter.
/// For example, to enforce that the `{` and `}` of an object expression are formatted on the same line
/// as the `(` and `)` tokens even IF the object expression itself breaks across multiple lines.
///
/// ```javascript
/// function test({
/// aVeryLongObjectBinding,
/// thatContinuesAndExceeds,
/// theLineWidth
/// }) {}
/// ```
Hug,
/// The default layout formats all parameters on the same line if they fit or breaks after the `(`
/// and before the `(`.
/// ```javascript
/// function test(
/// firstParameter,
/// secondParameter,
/// thirdParameter
/// ) {}
/// ```
Default,
}
pub(crate) fn should_hug_function_parameters(
parameters: &FormatAnyJsParameters,
comments: &JsComments,
) -> FormatResult<bool> {
use rome_js_syntax::{
AnyJsBinding::*, AnyJsBindingPattern::*, AnyJsExpression::*, AnyJsFormalParameter::*,
AnyJsParameter::*,
};
let list = parameters.list();
if list.len() != 1 {
return Ok(false);
}
// SAFETY: Safe because of the length check above
let only_parameter = list.first().unwrap()?;
if comments.has_comments(only_parameter.syntax()) {
return Ok(false);
}
/// Returns true if the first parameter should be forced onto the same line as the `(` and `)` parentheses.
/// See the `[ParameterLayout::Hug] documentation.
fn hug_formal_parameter(parameter: &self::AnyJsFormalParameter) -> FormatResult<bool> {
let result = match parameter {
JsFormalParameter(parameter) => {
match parameter.initializer() {
None => {
match parameter.binding()? {
// always true for `[a]` or `{a}`
JsArrayBindingPattern(_) | JsObjectBindingPattern(_) => true,
// only if the type parameter is an object type
// `a: { prop: string }`
AnyJsBinding(JsIdentifierBinding(_)) => parameter
.type_annotation()
.map_or(false, |type_annotation| {
matches!(type_annotation.ty(), Ok(AnyTsType::TsObjectType(_)))
}),
AnyJsBinding(JsBogusBinding(_)) => {
return Err(FormatError::SyntaxError);
}
}
}
Some(initializer) => {
// only for `[a] = []`, `{a} = {}`
let object_or_array_binding = matches!(
parameter.binding()?,
JsArrayBindingPattern(_) | JsObjectBindingPattern(_)
);
let should_hug_right = match initializer.expression()? {
JsObjectExpression(object) => object.members().is_empty(),
JsArrayExpression(array) => array.elements().is_empty(),
JsIdentifierExpression(_) => true,
_ => false,
};
object_or_array_binding && should_hug_right
}
}
}
JsBogusParameter(_) => return Err(FormatError::SyntaxError),
};
Ok(result)
}
let result = match only_parameter {
AnyParameter::AnyJsParameter(parameter) => match parameter {
AnyJsFormalParameter(formal_parameter) => hug_formal_parameter(&formal_parameter)?,
JsRestParameter(_) => false,
TsThisParameter(this) => this.type_annotation().map_or(false, |type_annotation| {
matches!(type_annotation.ty(), Ok(AnyTsType::TsObjectType(_)))
}),
},
AnyParameter::AnyJsConstructorParameter(constructor_parameter) => {
match constructor_parameter {
AnyJsConstructorParameter::AnyJsFormalParameter(formal_parameter) => {
hug_formal_parameter(&formal_parameter)?
}
AnyJsConstructorParameter::JsRestParameter(_)
| AnyJsConstructorParameter::TsPropertyParameter(_) => false,
}
}
};
Ok(result)
}
| 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/constructor_parameters.rs | crates/rome_js_formatter/src/js/bindings/constructor_parameters.rs | use crate::prelude::*;
use crate::js::bindings::parameters::FormatAnyJsParameters;
use rome_js_syntax::JsConstructorParameters;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsConstructorParameters;
impl FormatNodeRule<JsConstructorParameters> for FormatJsConstructorParameters {
fn fmt_fields(&self, node: &JsConstructorParameters, f: &mut JsFormatter) -> FormatResult<()> {
FormatAnyJsParameters::from(node.clone()).fmt(f)
}
fn fmt_dangling_comments(
&self,
_: &JsConstructorParameters,
_: &mut JsFormatter,
) -> FormatResult<()> {
// Formatted inside of `FormatJsAnyParameters
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/array_binding_pattern_rest_element.rs | crates/rome_js_formatter/src/js/bindings/array_binding_pattern_rest_element.rs | use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::JsArrayBindingPatternRestElement;
use rome_js_syntax::JsArrayBindingPatternRestElementFields;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsArrayBindingPatternRestElement;
impl FormatNodeRule<JsArrayBindingPatternRestElement> for FormatJsArrayBindingPatternRestElement {
fn fmt_fields(
&self,
node: &JsArrayBindingPatternRestElement,
f: &mut JsFormatter,
) -> FormatResult<()> {
let JsArrayBindingPatternRestElementFields {
dotdotdot_token,
pattern,
} = node.as_fields();
write![f, [dotdotdot_token.format(), pattern.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_rest.rs | crates/rome_js_formatter/src/js/bindings/object_binding_pattern_rest.rs | use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::JsObjectBindingPatternRest;
use rome_js_syntax::JsObjectBindingPatternRestFields;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsObjectBindingPatternRest;
impl FormatNodeRule<JsObjectBindingPatternRest> for FormatJsObjectBindingPatternRest {
fn fmt_fields(
&self,
node: &JsObjectBindingPatternRest,
f: &mut JsFormatter,
) -> FormatResult<()> {
let JsObjectBindingPatternRestFields {
dotdotdot_token,
binding,
} = node.as_fields();
write![f, [dotdotdot_token.format(), binding.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/array_binding_pattern.rs | crates/rome_js_formatter/src/js/bindings/array_binding_pattern.rs | use crate::prelude::*;
use rome_formatter::write;
use rome_js_syntax::JsArrayBindingPattern;
use rome_js_syntax::JsArrayBindingPatternFields;
#[derive(Debug, Clone, Default)]
pub(crate) struct FormatJsArrayBindingPattern;
impl FormatNodeRule<JsArrayBindingPattern> for FormatJsArrayBindingPattern {
fn fmt_fields(&self, node: &JsArrayBindingPattern, f: &mut JsFormatter) -> FormatResult<()> {
let JsArrayBindingPatternFields {
l_brack_token,
elements,
r_brack_token,
} = node.as_fields();
write!(f, [l_brack_token.format(),])?;
if elements.is_empty() {
write!(
f,
[format_dangling_comments(node.syntax()).with_block_indent()]
)?;
} else {
write!(f, [group(&soft_block_indent(&elements.format()))])?;
}
write!(f, [r_brack_token.format()])
}
fn fmt_dangling_comments(
&self,
_: &JsArrayBindingPattern,
_: &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/bindings/mod.rs | crates/rome_js_formatter/src/js/bindings/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_binding_pattern;
pub(crate) mod array_binding_pattern_rest_element;
pub(crate) mod binding_pattern_with_default;
pub(crate) mod constructor_parameters;
pub(crate) mod formal_parameter;
pub(crate) mod identifier_binding;
pub(crate) mod object_binding_pattern;
pub(crate) mod object_binding_pattern_property;
pub(crate) mod object_binding_pattern_rest;
pub(crate) mod object_binding_pattern_shorthand_property;
pub(crate) mod parameters;
pub(crate) mod rest_parameter;
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.