Skip to content

Conversation

@Dunqing
Copy link
Member

@Dunqing Dunqing commented Oct 27, 2025

I found a case where Oxfmt's output differs from Prettier. Honestly, I think the Oxfmt output is prettier than Prettier.
Anyway, I investigated this case to find the root cause.

Failed example

Input:

const defaultColorDecoratorsEnablement = accessor
  .get(IConfigurationService)
  .getValue<"auto" | "always" | "never">(
    "longlonglonglonglonglonglonglonglong",
  );

Oxfmt and Biome's output:

const defaultColorDecoratorsEnablement = accessor
  .get(IConfigurationService)
  .getValue<"auto" | "always" | "never">(
    "longlonglonglonglonglonglonglonglong",
  );

Prettier output:

const defaultColorDecoratorsEnablement = accessor
  .get(IConfigurationService)
  .getValue<
    "auto" | "always" | "never"
  >("longlonglonglonglonglonglonglonglong");

Investigating the cause

Initially, I think the problem is that we generate inconsistent IR, so the output is different, which is a reasonable suspicion because, so far, almost all issues are due to this reason. However, after carefully comparing both IR of Oxfmt and Prettier, they are essentially the same, so the problem is moved to the printing IR part.

After spending a few days on this case, I finally found the reason why they produce the same IR but print different outputs. The cause is inside the BestFitting, which is a graceful solution for Prettier's conditionalGroup.

Let's take a look at how Prettier handles conditionalGroup

Prettier implementation:

conditionalGroup
https://github.com/prettier/prettier/blob/7584432401a47a26943dd7a9ca9a8e032ead7285/src/document/builders.js#L99-L106

/**
 * @param {Doc[]} states
 * @param {object} [opts] - TBD ???
 * @returns Doc
 */
function conditionalGroup(states, opts) {
  return group(states[0], { ...opts, expandedStates: states });
}

handling of conditionalGroup
https://github.com/prettier/prettier/blob/7584432401a47a26943dd7a9ca9a8e032ead7285/src/document/printer.js#L408-L445

// Expanded states are a rare case where a document
// can manually provide multiple representations of
// itself. It provides an array of documents
// going from the least expanded (most flattened)
// representation first to the most expanded. If a
// group has these, we need to manually go through
// these states and find the first one that fits.
// eslint-disable-next-line no-lonely-if
if (doc.expandedStates) {
  const mostExpanded = doc.expandedStates.at(-1);

  if (doc.break) {
    cmds.push({ ind, mode: MODE_BREAK, doc: mostExpanded });

    break;
  } else {
    for (let i = 1; i < doc.expandedStates.length + 1; i++) {
      if (i >= doc.expandedStates.length) {
        cmds.push({ ind, mode: MODE_BREAK, doc: mostExpanded });

        break;
      } else {
        const state = doc.expandedStates[i];
        /** @type {Command} */
        const cmd = { ind, mode: MODE_FLAT, doc: state };

        if (fits(cmd, cmds, rem, hasLineSuffix, groupModeMap)) {
          cmds.push(cmd);

          break;
        }
      }
    }
  }
} else {
  cmds.push({ ind, mode: MODE_BREAK, doc: doc.contents });
}

Oxfmt implementation

fn print_best_fitting(
&mut self,
best_fitting: &'a BestFittingElement,
queue: &mut PrintQueue<'a>,
stack: &mut PrintCallStack,
indent_stack: &mut PrintIndentStack,
) -> PrintResult<()> {
let args = stack.top();
if args.mode().is_flat() && self.state.measured_group_fits {
queue.extend_back(best_fitting.most_flat());
self.print_entry(queue, stack, indent_stack, args)
} else {
self.state.measured_group_fits = true;
let normal_variants = &best_fitting.variants()[..best_fitting.variants().len() - 1];
for variant in normal_variants {
// Test if this variant fits and if so, use it. Otherwise try the next
// variant.
// Try to fit only the first variant on a single line
if !matches!(variant.first(), Some(&FormatElement::Tag(Tag::StartEntry))) {
return invalid_start_tag(TagKind::Entry, variant.first());
}
let entry_args = args.with_print_mode(PrintMode::Flat);
// Skip the first element because we want to override the args for the entry and the
// args must be popped from the stack as soon as it sees the matching end entry.
let content = &variant[1..];
queue.extend_back(content);
stack.push(TagKind::Entry, entry_args);
let variant_fits = self.fits(queue, stack, indent_stack)?;
stack.pop(TagKind::Entry)?;
// Remove the content slice because printing needs the variant WITH the start entry
let popped_slice = queue.pop_slice();
debug_assert_eq!(popped_slice, Some(content));
if variant_fits {
queue.extend_back(variant);
return self.print_entry(queue, stack, indent_stack, entry_args);
}
}
// No variant fits, take the last (most expanded) as fallback
let most_expanded = best_fitting.most_expanded();
queue.extend_back(most_expanded);
self.print_entry(queue, stack, indent_stack, args.with_print_mode(PrintMode::Expanded))
}
}

The difference between the implementations is in handling different expandedStates (Called as variants in Oxfmt).

In prettier, it will try to get all expandedStates to check whether they fit or not in the MODE_FLAT mode. If not, they will fall back to the mostExpanded and print it in MODE_BREAK mode.

In Oxfmt, it will try to get all variants except the last one (most expanded) to check whether they fit or not in the PrintMode::Flat mode. If not, they will fall back to the mostExpanded and print it in PrintMode::Expanded mode.

So the root cause is Oxfmt, which doesn't check the mostExpanded one, whether it fits in the PrintMode::Fit mode. After aligning this, the issue was solved.

Thinking

After understanding the use of conditionalGroup, although this issue is due to Oxfmt not exactly aligning with Prettier's behavior, I suspect this is a bug in Prettier because mostExpanded is expected to be printed in break mode, but Prettier prints it in flat mode if it fits. It's not intuitive, and it's not as if the variable names describe it. Additionally, this case is a little complex, and the Prettier tests don't include such cases, so the Prettier team probably wasn't aware of this case.

Copy link
Member Author

Dunqing commented Oct 27, 2025


How to use the Graphite Merge Queue

Add either label to this PR to merge it via the merge queue:

  • 0-merge - adds this PR to the back of the merge queue
  • hotfix - for urgent hot fixes, skip the queue and merge this PR next

You must have a Graphite account in order to use the merge queue. Sign up using this link.

An organization admin has enabled the Graphite Merge Queue in this repository.

Please do not merge from GitHub as this will restart CI on PRs being processed by the merge queue.

This stack of pull requests is managed by Graphite. Learn more about stacking.

@codspeed-hq
Copy link

codspeed-hq bot commented Oct 27, 2025

CodSpeed Performance Report

Merging #14983 will not alter performance

Comparing 10-27-fix_formatter_bestfitting_doesn_t_exactly_matches_the_conditinalgroup_behavior_in_prettier (54c509e) with 10-25-fix_formatter_lign_the_logic_of_printing_type_parameters_parameters_and_return_type_for_functions_with_prettier (63c324d)

Summary

✅ 33 untouched
⏩ 4 skipped1

Footnotes

  1. 4 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.

@Dunqing Dunqing marked this pull request as ready for review October 27, 2025 08:46
@graphite-app graphite-app bot added the 0-merge Merge with Graphite Merge Queue label Oct 27, 2025
@graphite-app
Copy link
Contributor

graphite-app bot commented Oct 27, 2025

Merge activity

…Group` behavior in Prettier (#14983)

I found a case where Oxfmt's output differs from Prettier. Honestly, I think the `Oxfmt` output is prettier than `Prettier`.
Anyway, I investigated this case to find the root cause.

### Failed example

Input:
```ts
const defaultColorDecoratorsEnablement = accessor
  .get(IConfigurationService)
  .getValue<"auto" | "always" | "never">(
    "longlonglonglonglonglonglonglonglong",
  );
```

Oxfmt and Biome's output:
```ts
const defaultColorDecoratorsEnablement = accessor
  .get(IConfigurationService)
  .getValue<"auto" | "always" | "never">(
    "longlonglonglonglonglonglonglonglong",
  );
```

Prettier output:
```ts
const defaultColorDecoratorsEnablement = accessor
  .get(IConfigurationService)
  .getValue<
    "auto" | "always" | "never"
  >("longlonglonglonglonglonglonglonglong");
```
### Investigating the cause

Initially, I think the problem is that we generate inconsistent `IR`, so the output is different, which is a reasonable suspicion because, so far, almost all issues are due to this reason. However, after carefully comparing both IR of Oxfmt and Prettier, they are essentially the same, so the problem is moved to the printing IR part.

After spending a few days on this case, I finally found the reason why they produce the same IR but print different outputs. The cause is inside the `BestFitting`, which is a graceful solution for Prettier's `conditionalGroup`.

Let's take a look at how Prettier handles `conditionalGroup`

#### Prettier implementation:
**conditionalGroup**
https://github.com/prettier/prettier/blob/7584432401a47a26943dd7a9ca9a8e032ead7285/src/document/builders.js#L99-L106
```js
/**
 * @param {Doc[]} states
 * @param {object} [opts] - TBD ???
 * @returns Doc
 */
function conditionalGroup(states, opts) {
  return group(states[0], { ...opts, expandedStates: states });
}
```

**handling of conditionalGroup**
https://github.com/prettier/prettier/blob/7584432401a47a26943dd7a9ca9a8e032ead7285/src/document/printer.js#L408-L445
```js
// Expanded states are a rare case where a document
// can manually provide multiple representations of
// itself. It provides an array of documents
// going from the least expanded (most flattened)
// representation first to the most expanded. If a
// group has these, we need to manually go through
// these states and find the first one that fits.
// eslint-disable-next-line no-lonely-if
if (doc.expandedStates) {
  const mostExpanded = doc.expandedStates.at(-1);

  if (doc.break) {
    cmds.push({ ind, mode: MODE_BREAK, doc: mostExpanded });

    break;
  } else {
    for (let i = 1; i < doc.expandedStates.length + 1; i++) {
      if (i >= doc.expandedStates.length) {
        cmds.push({ ind, mode: MODE_BREAK, doc: mostExpanded });

        break;
      } else {
        const state = doc.expandedStates[i];
        /** @type {Command} */
        const cmd = { ind, mode: MODE_FLAT, doc: state };

        if (fits(cmd, cmds, rem, hasLineSuffix, groupModeMap)) {
          cmds.push(cmd);

          break;
        }
      }
    }
  }
} else {
  cmds.push({ ind, mode: MODE_BREAK, doc: doc.contents });
}
```

#### Oxfmt implementation

https://github.com/oxc-project/oxc/blob/d9f7df8bc6bf7e48c90ba99638502c87afba0e04/crates/oxc_formatter/src/formatter/printer/mod.rs#L366-L418

The difference between the implementations is in handling different `expandedStates` (Called as `variants` in Oxfmt).

In prettier, they will try to get all `expandedStates` except the first one to check whether they fit or not in the `MODE_FLAT` mode. If not, they will fall back to the `mostExpanded` and print it in `MODE_BREAK` mode.
@graphite-app graphite-app bot force-pushed the 10-25-fix_formatter_lign_the_logic_of_printing_type_parameters_parameters_and_return_type_for_functions_with_prettier branch from 63c324d to 4a84e44 Compare October 27, 2025 09:36
@graphite-app graphite-app bot requested a review from overlookmotel as a code owner October 27, 2025 09:36
@graphite-app graphite-app bot force-pushed the 10-27-fix_formatter_bestfitting_doesn_t_exactly_matches_the_conditinalgroup_behavior_in_prettier branch from 54c509e to 3940f3a Compare October 27, 2025 09:36
@graphite-app graphite-app bot removed the 0-merge Merge with Graphite Merge Queue label Oct 27, 2025
Base automatically changed from 10-25-fix_formatter_lign_the_logic_of_printing_type_parameters_parameters_and_return_type_for_functions_with_prettier to main October 27, 2025 09:47
@graphite-app graphite-app bot merged commit 3940f3a into main Oct 27, 2025
21 checks passed
@graphite-app graphite-app bot deleted the 10-27-fix_formatter_bestfitting_doesn_t_exactly_matches_the_conditinalgroup_behavior_in_prettier branch October 27, 2025 09:48
@Boshen Boshen mentioned this pull request Oct 30, 2025
leaysgur added a commit that referenced this pull request Oct 30, 2025
## [0.9.0] - 2025-10-30

### 🚀 Features

- 8fe7e85 formatter: Support printing Formatter IR (#14855) (Dunqing)

### 🐛 Bug Fixes

- a6b6ef8 formatter: Correct calculating layout for
`TSNonNullExpression` in `StaticMemberExpression` (#15065) (Dunqing)
- 99bd995 formatter: Print parenthesis for sequence expression in
`ReturnStatement` and `ExpressionStatement` (#15062) (Dunqing)
- f3fb998 formatter: Correct printing comments for `TSAsExpression`
(#15061) (Dunqing)
- 1e4a018 formatter: Correct checking of the short argument for
`CallArguments` (#15055) (Dunqing)
- c0dfd9b formatter: Print comments before fat arrow as-is for
`ArrowFunctionExpression` (#15050) (Dunqing)
- 206b519 formatter: Should hug parameter with `TSMappedType` type
annotation (#15049) (Dunqing)
- e48c604 formatter: Incorrect formatting of a function with `this`
parameter (#15031) (Dunqing)
- a9f0c45 formatter: Decorators and class method on the same line
shouldn't be broken by a leading comment of the method (#15029)
(Dunqing)
- 43d74e4 formatter: Handle `<CRLF>` for `SourceText` (#15016)
(leaysgur)
- 34fab40 formatter: Correct calculating layout for `ChainExpression` in
`StaticMemberExpression` (#14986) (Dunqing)
- 68dc101 formatter: Should not break when the parent of root of
`StaticMemberExpression` is used as the `Argument` of `NewExpression`
(#14985) (Dunqing)
- 071b739 formatter: Align the short argument handling for
UnaryExpression with Prettier (#14984) (Dunqing)
- 3940f3a formatter: `BestFitting` doesn't exactly matches the
`conditinalGroup` behavior in Prettier (#14983) (Dunqing)
- 4a84e44 formatter: Align the logic of printing type parameters,
parameters, and return type for functions with Prettier (#14942)
(Dunqing)
- 68c1f2a formatter: Non-nested static member expressions will never
break (#14929) (Dunqing)
- 42adc47 formatter: Check whether a type alias is complex when its
right hand side never break (#14928) (Dunqing)
- e501f13 formatter: Should not add a trailing comma for long curried
calls when `trailingComma` is es5 (#14913) (Dunqing)

### 🚜 Refactor

- 7d64291 formatter: Simplify printing ClassElement with a semicolon
(#15030) (Dunqing)
- 5de99c2 formatter: Export unified way to get_parse_options (#15027)
(leaysgur)
- f6f22e2 formatter: Clean up unneeded implementations for printing
comments (#14935) (Dunqing)
- 7a2b9d1 formatter: Improve printing trailing comments (#14934)
(Dunqing)
- ba10caa formatter: Align printing trailing comments with Prettier
(#14927) (Dunqing)
- 597c9e8 formatter: Remove redundunt public API (#14915) (leaysgur)

### ⚡ Performance

- 467b3a1 formatter: Optimize grouping logic for call arguments (#15033)
(Dunqing)

Co-authored-by: leaysgur <6259812+leaysgur@users.noreply.github.com>
@Boshen Boshen mentioned this pull request Oct 30, 2025
graphite-app bot pushed a commit that referenced this pull request Oct 30, 2025
## [0.9.0] - 2025-10-30

### 🚀 Features

- 8fe7e85 formatter: Support printing Formatter IR (#14855) (Dunqing)

### 🐛 Bug Fixes

- a6b6ef8 formatter: Correct calculating layout for `TSNonNullExpression` in `StaticMemberExpression` (#15065) (Dunqing)
- 99bd995 formatter: Print parenthesis for sequence expression in `ReturnStatement` and `ExpressionStatement` (#15062) (Dunqing)
- f3fb998 formatter: Correct printing comments for `TSAsExpression` (#15061) (Dunqing)
- 1e4a018 formatter: Correct checking of the short argument for `CallArguments` (#15055) (Dunqing)
- c0dfd9b formatter: Print comments before fat arrow as-is for `ArrowFunctionExpression` (#15050) (Dunqing)
- 206b519 formatter: Should hug parameter with `TSMappedType` type annotation (#15049) (Dunqing)
- e48c604 formatter: Incorrect formatting of a function with `this` parameter (#15031) (Dunqing)
- a9f0c45 formatter: Decorators and class method on the same line shouldn't be broken by a leading comment of the method (#15029) (Dunqing)
- 43d74e4 formatter: Handle `<CRLF>` for `SourceText` (#15016) (leaysgur)
- 34fab40 formatter: Correct calculating layout for `ChainExpression` in `StaticMemberExpression` (#14986) (Dunqing)
- 68dc101 formatter: Should not break when the parent of root of `StaticMemberExpression` is used as the `Argument` of `NewExpression` (#14985) (Dunqing)
- 071b739 formatter: Align the short argument handling for UnaryExpression with Prettier (#14984) (Dunqing)
- 3940f3a formatter: `BestFitting` doesn't exactly matches the `conditinalGroup` behavior in Prettier (#14983) (Dunqing)
- 4a84e44 formatter: Align the logic of printing type parameters, parameters, and return type for functions with Prettier (#14942) (Dunqing)
- 68c1f2a formatter: Non-nested static member expressions will never break (#14929) (Dunqing)
- 42adc47 formatter: Check whether a type alias is complex when its right hand side never break (#14928) (Dunqing)
- e501f13 formatter: Should not add a trailing comma for long curried calls when `trailingComma` is es5 (#14913) (Dunqing)

### 🚜 Refactor

- 7d64291 formatter: Simplify printing ClassElement with a semicolon (#15030) (Dunqing)
- 5de99c2 formatter: Export unified way to get_parse_options (#15027) (leaysgur)
- f6f22e2 formatter: Clean up unneeded implementations for printing comments (#14935) (Dunqing)
- 7a2b9d1 formatter: Improve printing trailing comments (#14934) (Dunqing)
- ba10caa formatter: Align printing trailing comments with Prettier (#14927) (Dunqing)
- 597c9e8 formatter: Remove redundunt public API (#14915) (leaysgur)

### ⚡ Performance

- 467b3a1 formatter: Optimize grouping logic for call arguments (#15033) (Dunqing)

### 💼 Other

- aceff66 oxfmt: V0.9.0 (#15088) (Boshen)
@Boshen Boshen mentioned this pull request Oct 30, 2025
graphite-app bot pushed a commit that referenced this pull request Oct 30, 2025
## [0.9.0] - 2025-10-30

### 🚀 Features

- 8fe7e85 formatter: Support printing Formatter IR (#14855) (Dunqing)

### 🐛 Bug Fixes

- a6b6ef8 formatter: Correct calculating layout for `TSNonNullExpression` in `StaticMemberExpression` (#15065) (Dunqing)
- 99bd995 formatter: Print parenthesis for sequence expression in `ReturnStatement` and `ExpressionStatement` (#15062) (Dunqing)
- f3fb998 formatter: Correct printing comments for `TSAsExpression` (#15061) (Dunqing)
- 1e4a018 formatter: Correct checking of the short argument for `CallArguments` (#15055) (Dunqing)
- c0dfd9b formatter: Print comments before fat arrow as-is for `ArrowFunctionExpression` (#15050) (Dunqing)
- 206b519 formatter: Should hug parameter with `TSMappedType` type annotation (#15049) (Dunqing)
- e48c604 formatter: Incorrect formatting of a function with `this` parameter (#15031) (Dunqing)
- a9f0c45 formatter: Decorators and class method on the same line shouldn't be broken by a leading comment of the method (#15029) (Dunqing)
- 43d74e4 formatter: Handle `<CRLF>` for `SourceText` (#15016) (leaysgur)
- 34fab40 formatter: Correct calculating layout for `ChainExpression` in `StaticMemberExpression` (#14986) (Dunqing)
- 68dc101 formatter: Should not break when the parent of root of `StaticMemberExpression` is used as the `Argument` of `NewExpression` (#14985) (Dunqing)
- 071b739 formatter: Align the short argument handling for UnaryExpression with Prettier (#14984) (Dunqing)
- 3940f3a formatter: `BestFitting` doesn't exactly matches the `conditinalGroup` behavior in Prettier (#14983) (Dunqing)
- 4a84e44 formatter: Align the logic of printing type parameters, parameters, and return type for functions with Prettier (#14942) (Dunqing)
- 68c1f2a formatter: Non-nested static member expressions will never break (#14929) (Dunqing)
- 42adc47 formatter: Check whether a type alias is complex when its right hand side never break (#14928) (Dunqing)
- e501f13 formatter: Should not add a trailing comma for long curried calls when `trailingComma` is es5 (#14913) (Dunqing)

### 🚜 Refactor

- 7d64291 formatter: Simplify printing ClassElement with a semicolon (#15030) (Dunqing)
- 5de99c2 formatter: Export unified way to get_parse_options (#15027) (leaysgur)
- f6f22e2 formatter: Clean up unneeded implementations for printing comments (#14935) (Dunqing)
- 7a2b9d1 formatter: Improve printing trailing comments (#14934) (Dunqing)
- ba10caa formatter: Align printing trailing comments with Prettier (#14927) (Dunqing)
- 597c9e8 formatter: Remove redundunt public API (#14915) (leaysgur)

### ⚡ Performance

- 467b3a1 formatter: Optimize grouping logic for call arguments (#15033) (Dunqing)

### 💼 Other

- 6368793 oxfmt: V0.9.0 (#15091) (Boshen)
- aceff66 oxfmt: V0.9.0 (#15088) (Boshen)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-formatter Area - Formatter C-bug Category - Bug

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants