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 16 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
4 changes: 1 addition & 3 deletions .eslintrc.yml
@@ -1,12 +1,10 @@
root: true
env:
es6: true
es2020: true
node: true
extends:
- eslint:recommended
- plugin:prettier/recommended
parserOptions:
ecmaVersion: 2018
plugins:
- import
- unicorn
Expand Down
42 changes: 42 additions & 0 deletions changelog_unreleased/javascript/pr-8508.md
@@ -0,0 +1,42 @@
#### 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,
};
```

Note that Prettier only touches “simple” numbers such as `1` and `123.5`. It _won’t_ make the following transformations, as they feel unexpected:

```
1e2 -> "100"
0b10 -> "10"
1_000 -> "1000"
1.0 -> "1"
0.99999999999999999 -> "1"
999999999999999999999 -> "1e+21"
2n -> "2"

"1e+100" -> 1e+100
```

(As a side note, please don’t use confusing numbers as object keys!)
5 changes: 4 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 (some) number keys.
if (
(ast.type === "Property" ||
ast.type === "ObjectProperty" ||
Expand All @@ -89,6 +91,7 @@ function clean(ast, newObj, parent) {
typeof ast.key === "object" &&
ast.key &&
(ast.key.type === "Literal" ||
ast.key.type === "NumericLiteral" ||
ast.key.type === "StringLiteral" ||
ast.key.type === "Identifier")
) {
Expand Down
33 changes: 27 additions & 6 deletions src/language-js/printer-estree.js
Expand Up @@ -68,12 +68,14 @@ const {
isMemberExpressionChain,
isMemberish,
isNgForOf,
isNumericLiteral,
isObjectType,
isObjectTypePropertyAFunction,
isSimpleFlowType,
isSimpleNumber,
isSimpleTemplateLiteral,
isStringLiteral,
isStringPropSafeToCoerceToIdentifier,
isStringPropSafeToUnquote,
isTemplateOnItsOwnLine,
isTestCall,
isTheOnlyJSXElementInMarkdown,
Expand Down Expand Up @@ -3734,32 +3736,51 @@ 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) &&
isSimpleNumber(printNumber(rawText(key))) &&
// Avoid converting 999999999999999999999 to 1e+21, 0.99999999999999999 to 1 and 1.0 to 1.
String(key.value) === printNumber(rawText(key)) &&
!(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);
// 1 -> "1"
// 1.5 -> "1.5"
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
// '1' -> 1
// '1.5' -> 1.5
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
53 changes: 43 additions & 10 deletions src/language-js/utils.js
Expand Up @@ -734,21 +734,53 @@ 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"
)) ||
(isSimpleNumber(node.key.value) &&
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
);
}

// Matches “simple” numbers like `123` and `2.5` but not `1_000`, `1e+100` or `0b10`.
function isSimpleNumber(numberString) {
return /^(\d+|\d+\.\d+)$/.test(numberString);
}

function isJestEachTemplateLiteral(node, parentNode) {
/**
* describe.each`table`(name, fn)
Expand Down Expand Up @@ -1101,9 +1133,10 @@ module.exports = {
isObjectType,
isObjectTypePropertyAFunction,
isSimpleFlowType,
isSimpleNumber,
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"]);