Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Quote and unquote number keys #8508

Merged
merged 19 commits into from Jun 18, 2020
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
26 changes: 26 additions & 0 deletions changelog_unreleased/javascript/pr-8508.md
@@ -0,0 +1,26 @@
#### Quote and unquote number keys ([#8508](https://github.com/prettier/prettier/pull/8508) by [@lydell](https://github.com/lydell))

Prettier removes quotes from object keys if they are identifiers. Now, Prettier also removes quotes from object keys that are numbers.

If you use `quoteProps: "consistent"`, Prettier can also _add_ quotes to number keys so that _all_ properties end up with quotes.

<!-- prettier-ignore -->
```jsx
// Input
x = {
"a": null,
"1": null,
};

// Prettier stable
x = {
a: null,
"1": null,
};

// Prettier master
x = {
a: null,
1: null,
};
```
6 changes: 5 additions & 1 deletion src/language-js/clean.js
Expand Up @@ -78,7 +78,9 @@ function clean(ast, newObj, parent) {
delete newObj.closingElement;
}

// We change {'key': value} into {key: value}
// We change {'key': value} into {key: value}.
// And {key: value} into {'key': value}.
// Also for number keys.
if (
(ast.type === "Property" ||
ast.type === "ObjectProperty" ||
Expand All @@ -89,6 +91,8 @@ function clean(ast, newObj, parent) {
typeof ast.key === "object" &&
ast.key &&
(ast.key.type === "Literal" ||
ast.key.type === "NumericLiteral" ||
ast.key.type === "BigIntLiteral" ||
ast.key.type === "StringLiteral" ||
ast.key.type === "Identifier")
) {
Expand Down
28 changes: 22 additions & 6 deletions src/language-js/printer-estree.js
Expand Up @@ -68,12 +68,13 @@ const {
isMemberExpressionChain,
isMemberish,
isNgForOf,
isNumericLiteral,
isObjectType,
isObjectTypePropertyAFunction,
isSimpleFlowType,
isSimpleTemplateLiteral,
isStringLiteral,
isStringPropSafeToCoerceToIdentifier,
isStringPropSafeToUnquote,
isTemplateOnItsOwnLine,
isTestCall,
isTheOnlyJSXElementInMarkdown,
Expand Down Expand Up @@ -3734,32 +3735,47 @@ function printPropertyKey(path, options, print) {
!prop.computed &&
prop.key &&
isStringLiteral(prop.key) &&
!isStringPropSafeToCoerceToIdentifier(prop, options)
!isStringPropSafeToUnquote(prop, options)
);
needsQuoteProps.set(parent, objectHasStringProp);
}

if (
key.type === "Identifier" &&
(key.type === "Identifier" ||
((isNumericLiteral(key) || key.type === "BigIntLiteral") &&
!(options.parser === "typescript" || options.parser === "babel-ts"))) &&
(options.parser === "json" ||
(options.quoteProps === "consistent" && needsQuoteProps.get(parent)))
) {
// a -> "a"
const prop = printString(JSON.stringify(key.name), options);
// 1e2 -> "100"
// 2n -> "2"
const prop = printString(
JSON.stringify(
key.type === "Identifier" ? key.name : key.value.toString()
),
options
);
lydell marked this conversation as resolved.
Show resolved Hide resolved
return path.call(
(keyPath) => comments.printComments(keyPath, () => prop, options),
"key"
);
}

if (
isStringPropSafeToCoerceToIdentifier(node, options) &&
isStringPropSafeToUnquote(node, options) &&
(options.quoteProps === "as-needed" ||
(options.quoteProps === "consistent" && !needsQuoteProps.get(parent)))
) {
// 'a' -> a
// '1e+100' -> 1e100
return path.call(
(keyPath) => comments.printComments(keyPath, () => key.value, options),
(keyPath) =>
comments.printComments(
keyPath,
() => (/^\d/.test(key.value) ? printNumber(key.value) : key.value),
options
),
"key"
);
}
Expand Down
47 changes: 37 additions & 10 deletions src/language-js/utils.js
Expand Up @@ -734,18 +734,45 @@ function returnArgumentHasLeadingComment(options, argument) {
return false;
}

function isStringPropSafeToCoerceToIdentifier(node, options) {
// Note: Quoting/unquoting numbers in TypeScript is not safe.
//
// let a = { 1: 1, 2: 2 }
// let b = { '1': 1, '2': 2 }
//
// declare let aa: keyof typeof a;
// declare let bb: keyof typeof b;
//
// aa = bb;
// ^^
// Type '"1" | "2"' is not assignable to type '1 | 2'.
// Type '"1"' is not assignable to type '1 | 2'.(2322)
//
// And in Flow, you get:
//
// const x = {
// 0: 1
// ^ Non-string literal property keys not supported. [unsupported-syntax]
// }
function isStringPropSafeToUnquote(node, options) {
return (
options.parser !== "json" &&
isStringLiteral(node.key) &&
isIdentifierName(node.key.value) &&
rawText(node.key).slice(1, -1) === node.key.value &&
options.parser !== "json" &&
// With `--strictPropertyInitialization`, TS treats properties with quoted names differently than unquoted ones.
// See https://github.com/microsoft/TypeScript/pull/20075
!(
(options.parser === "typescript" || options.parser === "babel-ts") &&
node.type === "ClassProperty"
)
((isIdentifierName(node.key.value) &&
// With `--strictPropertyInitialization`, TS treats properties with quoted names differently than unquoted ones.
// See https://github.com/microsoft/TypeScript/pull/20075
!(
(options.parser === "typescript" || options.parser === "babel-ts") &&
node.type === "ClassProperty"
)) ||
(!node.key.value.startsWith("-") &&
String(Number(node.key.value)) === node.key.value &&
!(
options.parser === "flow" ||
options.parser === "babel-flow" ||
options.parser === "typescript" ||
options.parser === "babel-ts"
)))
thorn0 marked this conversation as resolved.
Show resolved Hide resolved
);
}

Expand Down Expand Up @@ -1103,7 +1130,7 @@ module.exports = {
isSimpleFlowType,
isSimpleTemplateLiteral,
isStringLiteral,
isStringPropSafeToCoerceToIdentifier,
isStringPropSafeToUnquote,
isTemplateOnItsOwnLine,
isTestCall,
isTheOnlyJSXElementInMarkdown,
Expand Down
Expand Up @@ -2,7 +2,7 @@

exports[`delegate_yield.js format 1`] = `
====================================options=====================================
parsers: ["flow", "babel"]
parsers: ["flow"]
printWidth: 80
| printWidth
=====================================input======================================
Expand Down Expand Up @@ -66,7 +66,7 @@ async function* delegate_return() {

exports[`generator.js format 1`] = `
====================================options=====================================
parsers: ["flow", "babel"]
parsers: ["flow"]
printWidth: 80
| printWidth
=====================================input======================================
Expand Down Expand Up @@ -128,7 +128,7 @@ async function f() {

exports[`return.js format 1`] = `
====================================options=====================================
parsers: ["flow", "babel"]
parsers: ["flow"]
printWidth: 80
| printWidth
=====================================input======================================
Expand Down Expand Up @@ -186,7 +186,7 @@ refuse_return()

exports[`throw.js format 1`] = `
====================================options=====================================
parsers: ["flow", "babel"]
parsers: ["flow"]
printWidth: 80
| printWidth
=====================================input======================================
Expand Down
2 changes: 1 addition & 1 deletion tests/flow-repo/async_iteration/jsfmt.spec.js
@@ -1 +1 @@
run_spec(__dirname, ["flow", "babel"]);
run_spec(__dirname, ["flow"]);