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

fix: check constant violation inside loops #15019

Merged
merged 1 commit into from Oct 8, 2022
Merged
Show file tree
Hide file tree
Changes from all 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
20 changes: 14 additions & 6 deletions packages/babel-plugin-transform-block-scoping/src/index.ts
@@ -1,5 +1,5 @@
import { declare } from "@babel/helper-plugin-utils";
import type { NodePath, Visitor, Scope } from "@babel/traverse";
import type { NodePath, Visitor, Scope, Binding } from "@babel/traverse";
import { visitor as tdzVisitor } from "./tdz";
import type { TDZVisitorState } from "./tdz";
import { traverse, template, types as t } from "@babel/core";
Expand Down Expand Up @@ -487,13 +487,21 @@ class BlockScoping {
}

checkConstants() {
const scope = this.scope;
const state = this.state;
const constBindings = new Map<string, Binding>();

// In some cases, there are two different scopes: for example,
// for (const x of y) {} has a scope for the loop head and one
// for the body.
for (const scope of new Set([this.scope, this.blockPath.scope])) {
for (const name of Object.keys(scope.bindings)) {
const binding = scope.bindings[name];
if (binding.kind === "const") constBindings.set(name, binding);
}
}

for (const name of Object.keys(scope.bindings)) {
const binding = scope.bindings[name];
if (binding.kind !== "const") continue;
const { state } = this;

for (const [name, binding] of constBindings) {
for (const violation of binding.constantViolations) {
const readOnlyError = state.addHelper("readOnlyError");
const throwNode = t.callExpression(readOnlyError, [
Expand Down
@@ -0,0 +1,11 @@
expect(function () {
for (const element = 1; element++;) break;
}).toThrow('"element" is read-only');

expect(function () {
for (;;) {
const from = 50;
from--;
break;
}
}).toThrow('"from" is read-only');
@@ -0,0 +1,4 @@
for (const element = 1; element++;) {
const from = 50;
from--;
}
@@ -0,0 +1,4 @@
for (var element = 1; +element, babelHelpers.readOnlyError("element");) {
var from = 50;
+from, babelHelpers.readOnlyError("from");
}
@@ -0,0 +1,7 @@
expect(function () {
const array = [1, 2, 3];
for (const element of array) {
const from = 50;
from--;
}
}).toThrow('"from" is read-only');
@@ -0,0 +1,4 @@
for (const element of []) {
const from = 50;
from--;
}
@@ -0,0 +1,4 @@
for (var element of []) {
var from = 50;
+from, babelHelpers.readOnlyError("from");
}