compiler: error on reassigning to const

We currently don't report an error if the code attempts to reassign a const. Our thinking has been that we're not trying to catch all possible mistakes you could make in JavaScript — that's what ESLint, TypeScript, and Flow are for — and that we want to focus on React errors. However, accidentally reassigning a const is easy to catch and doesn't get in the way of other analysis so let's implement it.

Note that React Compiler's ESLint plugin won't report these errors by default, but they will show up in playground.

Fixes #29598

ghstack-source-id: a0af8b9a48
Pull Request resolved: https://github.com/facebook/react/pull/29619
This commit is contained in:
Joe Savona committed 2024-05-28 13:09:17 -07:00
1 parent 97722ca3d4
commit 46339720d7
5 files changed
+49 -2

No files matched your search

@@ -3336,6 +3336,20 @@ function lowerIdentifierForAssignment(
});
return null;
}
} else if (
binding.bindingKind === "const" &&
kind === InstructionKind.Reassign
) {
builder.errors.push({
reason: `Cannot reassign a \`const\` variable`,
severity: ErrorSeverity.InvalidJS,
loc: path.node.loc ?? null,
description:
binding.identifier.name != null
? `\`${binding.identifier.name.value}\` is declared as const`
: null,
});
return null;
}
const place: Place = {
@@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import { BindingKind } from "@babel/traverse";
import * as t from "@babel/types";
import { CompilerError, CompilerErrorDetailOptions } from "../CompilerError";
import { assertExhaustive } from "../Utils/utils";
@@ -1105,7 +1106,7 @@ export type MutableRange = {
export type VariableBinding =
// let, const, etc declared within the current component/hook
| { kind: "Identifier"; identifier: Identifier }
| { kind: "Identifier"; identifier: Identifier; bindingKind: BindingKind }
// bindings declard outside the current component/hook
| NonLocalBinding;
@@ -280,7 +280,11 @@ export default class HIRBuilder {
if (resolvedBinding.name && resolvedBinding.name.value !== originalName) {
babelBinding.scope.rename(originalName, resolvedBinding.name.value);
}
return { kind: "Identifier", identifier: resolvedBinding };
return {
kind: "Identifier",
identifier: resolvedBinding,
bindingKind: babelBinding.kind,
};
}
isContextIdentifier(path: NodePath<t.Identifier | t.JSXIdentifier>): boolean {
@@ -0,0 +1,24 @@
## Input
```javascript
function Component() {
const x = 0;
x = 1;
}
```
## Error
```
1 | function Component() {
2 | const x = 0;
> 3 | x = 1;
| ^ InvalidJS: Cannot reassign a `const` variable. `x` is declared as const (3:3)
4 | }
5 |
```
@@ -0,0 +1,4 @@
function Component() {
const x = 0;
x = 1;
}