Skip to content

feat(formatter): support consistent quote props#16677

Merged
graphite-app[bot] merged 1 commit intomainfrom
12-10-feat_formatter_support_consistent_quote_props
Dec 11, 2025
Merged

feat(formatter): support consistent quote props#16677
graphite-app[bot] merged 1 commit intomainfrom
12-10-feat_formatter_support_consistent_quote_props

Conversation

@Dunqing
Copy link
Copy Markdown
Member

@Dunqing Dunqing commented Dec 10, 2025

Summary

close: #16247

The Prettier documentation is Quote props.

Support consistent in all object-like nodes, including ObjectExpression, Class, TSTypeLiteral, TSInterfaceDeclaration, and WithClause.

Example:

// ============================================
// ObjectExpression - object literals
// ============================================
const obj = {
  normal: "value",
  "needs-quote": "value",  // triggers consistent quoting for all keys
};

// Nested objects are handled independently
const nested = {
  outer: {
    inner: "value",
    "inner-key": "value",  // only inner object gets quoted
  },
  outerKey: "value",       // outer stays unquoted
};

// ============================================
// Class - properties, methods, and accessors
// ============================================
class MyClass {
  prop1 = "value";
  "prop-2" = "value";      // triggers consistent quoting

  method1() {}
  "method-2"() {}          // triggers consistent quoting for methods too

  get getter1() { return 1; }
  get "getter-2"() { return 2; }  // triggers consistent quoting for accessors too
  set setter1(v) {}
  set "setter-2"(v) {}
}

// ============================================
// WithClause - import/export attributes
// ============================================
import data from "./data.json" with {
  type: "json",
  "custom-attr": "value",  // triggers consistent quoting
};

export { foo } from "./foo.js" with {
  key: "value",
  "x-y": "other",
};

// ============================================
// TSInterfaceDeclaration (TypeScript)
// ============================================
interface MyInterface {
  prop1: string;
  "prop-2": number;        // triggers consistent quoting

  method1(): void;
  "method-2"(): string;    // triggers consistent quoting for method signatures too
}

// ============================================
// TSTypeLiteral (TypeScript)
// ============================================
type MyType = {
  field1: string;
  "field-2": number;       // triggers consistent quoting

  method(): void;
  "method-2"(): string;    // triggers consistent quoting for method signatures too
};

// Inline type literal
function process(param: { x: string; "y-z": number }): void {}

NOTE: I've found a Prettier bug, that is, TSMethodSignature is not being wrapped in quotes! But it should be, see Prettier Playground

Not implemented case

There are still two failed tests because NumericLiterals doesn't wrap in quotes in consistent, which is intended because Prettier only wraps them when the parser is JavaScript or Flow

For example:

Input:

const A = {
  "k-b": a,
  2: b,
}

Output:

With babel or flow parser

const A = {
  "k-b": a,
  "2": b,
};

With babel-ts or typescript parser

const A = {
  "k-b": a,
  2: b,
};

So, for simplicity, and since oxc includes parsing TS, we don't wrap NumericLiteral in quotes at all.

Tests

All tests are generated by Claude with the proper prompt, covering all code in this PR.

@github-actions github-actions bot added the A-formatter Area - Formatter label Dec 10, 2025
Copy link
Copy Markdown
Member Author

Dunqing commented Dec 10, 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.

@github-actions github-actions bot added the C-enhancement Category - New feature or request label Dec 10, 2025
@Dunqing Dunqing changed the title feat(formatter): support consistent quote props feat(formatter): support consistent quote props Dec 10, 2025
@codspeed-hq
Copy link
Copy Markdown

codspeed-hq bot commented Dec 10, 2025

CodSpeed Performance Report

Merging #16677 will not alter performance

Comparing 12-10-feat_formatter_support_consistent_quote_props (afc2f6b) with main (2495a39)

Summary

✅ 38 untouched
⏩ 7 skipped1

Footnotes

  1. 7 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 force-pushed the 12-10-feat_formatter_support_consistent_quote_props branch from 3cf06a5 to 615e8e8 Compare December 10, 2025 08:19
@Dunqing Dunqing marked this pull request as ready for review December 10, 2025 08:26
@Dunqing Dunqing requested review from Copilot and leaysgur December 10, 2025 08:26
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR implements support for the consistent quote properties option in the oxc formatter, matching Prettier's behavior. When enabled, if any property in an object-like structure requires quotes (e.g., "prop-2"), all properties in that structure will be consistently quoted.

Key changes:

  • Added stack-based quote tracking in FormatContext to handle nested object-like structures independently
  • Implemented consistent quoting for ObjectExpression, Class, TSTypeLiteral, TSInterfaceDeclaration, and WithClause
  • Refactored FormatLiteralStringToken::clean_text() to accept Formatter reference for accessing context state

Reviewed changes

Copilot reviewed 23 out of 23 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
crates/oxc_formatter/src/formatter/context.rs Added quote_needed_stack with push/pop/is_quote_needed methods for tracking quote consistency state
crates/oxc_formatter/src/options.rs Updated QuoteProperties::Consistent documentation to remove "NOT SUPPORTED YET" note; added QuoteStyle::as_str() helper
crates/oxc_formatter/src/utils/string.rs Refactored clean_text() to take Formatter reference; moved is_identifier_name_patched() to public API; changed is_quote_needed from enum-based to boolean
crates/oxc_formatter/src/utils/object.rs Added should_preserve_quote() helper to determine if property key requires quotes
crates/oxc_formatter/src/write/mod.rs Added quote wrapping for IdentifierName in property key contexts; added quote tracking for ObjectExpression and Vec<TSSignature>
crates/oxc_formatter/src/write/class.rs Added quote tracking for ClassBody covering properties, methods, and accessors
crates/oxc_formatter/src/write/import_declaration.rs Added quote tracking for WithClause in import/export attributes; updated ImportAttribute to use refactored clean_text()
crates/oxc_formatter/src/utils/assignment_like.rs Updated call to clean_text() with new signature
crates/oxc_formatter/tests/fixtures/mod.rs Added quoteProps option parsing support in test fixture configuration
crates/oxc_formatter/tests/fixtures/{js,ts}/quote-props/* Comprehensive test fixtures covering all supported node types with various quoting scenarios
tasks/prettier_conformance/src/lib.rs Removed filter skipping consistent quote properties tests
tasks/prettier_conformance/snapshots/prettier.js.snap.md Updated compatibility stats showing two expected failures for numeric literal handling (intentional deviation from Prettier)
Comments suppressed due to low confidence (1)

crates/oxc_formatter/src/formatter/context.rs:46

  • The Debug implementation for FormatContext does not include the newly added quote_needed_stack field. Consider adding it to the debug output for better debugging experience:
impl std::fmt::Debug for FormatContext<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FormatContext")
            .field("options", &self.options)
            .field("source_text", &self.source_text)
            .field("source_type", &self.source_type)
            .field("comments", &self.comments)
            .field("cached_elements", &self.cached_elements)
            .field("quote_needed_stack", &self.quote_needed_stack)
            .finish()
    }
}
impl std::fmt::Debug for FormatContext<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FormatContext")
            .field("options", &self.options)
            .field("source_text", &self.source_text)
            .field("source_type", &self.source_type)
            .field("comments", &self.comments)
            .field("cached_elements", &self.cached_elements)
            .finish()
    }

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Copy link
Copy Markdown
Member

@leaysgur leaysgur left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Dunqing I'll merge this now for subsequent tasks, but please check the following: 🙏🏻

  • Regarding Prettier bugs and behavior differences, please note them to the Diff Discussion (or report Prettier?)
  • The file tasks/coverage/acorn-test262 is probably unnecessary?

I think integration with Oxfmtrc is missing, but I'll handle that later.

@leaysgur leaysgur added the 0-merge Merge with Graphite Merge Queue label Dec 11, 2025
Copy link
Copy Markdown
Member

leaysgur commented Dec 11, 2025

Merge activity

### Summary

close: #16247

The Prettier documentation is [Quote props](https://prettier.io/docs/next/options#quote-props).

Support `consistent` in all object-like nodes, including `ObjectExpression`, `Class`, `TSTypeLiteral`, `TSInterfaceDeclaration`, and `WithClause`.

### Example:

```ts
// ============================================
// ObjectExpression - object literals
// ============================================
const obj = {
  normal: "value",
  "needs-quote": "value",  // triggers consistent quoting for all keys
};

// Nested objects are handled independently
const nested = {
  outer: {
    inner: "value",
    "inner-key": "value",  // only inner object gets quoted
  },
  outerKey: "value",       // outer stays unquoted
};

// ============================================
// Class - properties, methods, and accessors
// ============================================
class MyClass {
  prop1 = "value";
  "prop-2" = "value";      // triggers consistent quoting

  method1() {}
  "method-2"() {}          // triggers consistent quoting for methods too

  get getter1() { return 1; }
  get "getter-2"() { return 2; }  // triggers consistent quoting for accessors too
  set setter1(v) {}
  set "setter-2"(v) {}
}

// ============================================
// WithClause - import/export attributes
// ============================================
import data from "./data.json" with {
  type: "json",
  "custom-attr": "value",  // triggers consistent quoting
};

export { foo } from "./foo.js" with {
  key: "value",
  "x-y": "other",
};

// ============================================
// TSInterfaceDeclaration (TypeScript)
// ============================================
interface MyInterface {
  prop1: string;
  "prop-2": number;        // triggers consistent quoting

  method1(): void;
  "method-2"(): string;    // triggers consistent quoting for method signatures too
}

// ============================================
// TSTypeLiteral (TypeScript)
// ============================================
type MyType = {
  field1: string;
  "field-2": number;       // triggers consistent quoting

  method(): void;
  "method-2"(): string;    // triggers consistent quoting for method signatures too
};

// Inline type literal
function process(param: { x: string; "y-z": number }): void {}
```

NOTE: I've found a Prettier bug, that is, `TSMethodSignature` is not being wrapped in quotes! But it should be, see [Prettier Playground](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEMCeAHOACAtnGACwgBMBnbAXm2AB0ps8DiSAKASiWwDcIBLEgG56jAOT4ipALQAmURy68BwqAF8VIADQgIGGH2hlkoAIYAnMxADuABXMIjKEwBsrJtEe0AjMybABrAgBlE3wAGT4oOGQAMxcyOG0ILwArODAYAHVfDGQQDDM4BLNuaO9fAOCMP0iAc2QYMwBXRJAE3D4G5ta4AA8sMz58WBcAeQGTGAgzGwgyPn1oPIQSLRA+gaGEGBcAFTgzKHM+Itj41vmoWuc4AEUmiHgz5wTtFLJeoLqb+8fopDiL1aAEcHvAbJYMI5wIY+GR4IhtI0THxnHUAMIQXC4Ex5FzONaXa5wACCMEafC8TXBBwiUWerxAhBguGcmUICyK1TAcCCDgWfG4CzQeTAZE8IG4LQAklASNsgmBBnoSXKgugbgzWgU5nBsiZcigCkUDqU1itRjE6f8QM4YmtIsUYBCTLUcVrtNUzMU8l4TF44M4pDAJQVIlkBERkAAOAAM2kKoL4hRdbtxAPOSP9mUjhGQMm0TQSu39jkBjLguADJHlJDCJiuTVdcAAYtMceS6njqRAQKpVEA)

### Not implemented case

There are still two failed tests because NumericLiterals doesn't wrap in quotes in `consistent`, which is intended because Prettier only wraps them when the parser is `JavaScript` or `Flow`

For example:

Input:
```
const A = {
  "k-b": a,
  2: b,
}
```

Output:

With `babel` or `flow` parser
```ts
const A = {
  "k-b": a,
  "2": b,
};
```

With `babel-ts` or `typescript` parser

```ts
const A = {
  "k-b": a,
  2: b,
};
```

So, for simplicity, and since oxc includes parsing TS, we don't wrap `NumericLiteral` in quotes at all.

### Tests

All tests are generated by Claude with the proper prompt, covering all code in this PR.
@graphite-app graphite-app bot force-pushed the 12-10-feat_formatter_support_consistent_quote_props branch from afc2f6b to 686f2b7 Compare December 11, 2025 00:51
@graphite-app graphite-app bot merged commit 686f2b7 into main Dec 11, 2025
20 checks passed
@graphite-app graphite-app bot deleted the 12-10-feat_formatter_support_consistent_quote_props branch December 11, 2025 00:57
@graphite-app graphite-app bot removed the 0-merge Merge with Graphite Merge Queue label Dec 11, 2025
@Dunqing
Copy link
Copy Markdown
Member Author

Dunqing commented Dec 11, 2025

@Dunqing I'll merge this now for subsequent tasks, but please check the following: 🙏🏻

  • Regarding Prettier bugs and behavior differences, please note them to the Diff Discussion (or report Prettier?)

Will report to Prettier

  • The file tasks/coverage/acorn-test262 is probably unnecessary?

Opps, yes!

I think integration with Oxfmtrc is missing, but I'll handle that later.

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-formatter Area - Formatter C-enhancement Category - New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

formatter: Support quoteProps: "consistent" option

3 participants