From 21b2af8ba0b3b81e88887ac111be64041e7783ae Mon Sep 17 00:00:00 2001 From: Joe Savona Date: Wed, 24 Apr 2024 14:59:08 -0700 Subject: [PATCH] More precisely model for..of semantics with separate init/test blocks ghstack-source-id: 827c35466d04f7b7143ddf1adefeff926d4b22cd Pull Request resolved: https://github.com/facebook/react-forget/pull/2893 --- .../src/HIR/BuildHIR.ts | 21 ++- .../babel-plugin-react-forget/src/HIR/HIR.ts | 11 +- .../src/HIR/PrintHIR.ts | 8 +- .../src/HIR/visitors.ts | 18 ++- .../src/Inference/InferReferenceEffects.ts | 86 ++++++++--- .../ReactiveScopes/BuildReactiveFunction.ts | 26 ++++ .../ReactiveScopes/CodegenReactiveFunction.ts | 144 ++++++++++++++---- .../ReactiveScopes/PrintReactiveFunction.ts | 2 + .../ReactiveScopes/PruneNonEscapingScopes.ts | 24 ++- .../src/ReactiveScopes/visitors.ts | 5 + ...mutate-props-via-for-of-iterator.expect.md | 29 ++++ ...nvalid-mutate-props-via-for-of-iterator.js | 8 + ...p-with-context-variable-iterator.expect.md | 2 +- ...utate-later-value-initially-null.expect.md | 34 +++++ ...ction-mutate-later-value-initially-null.js | 13 ++ ...p-with-context-variable-iterator.expect.md | 2 +- ...of-local-collection-mutate-later.expect.md | 62 ++++++++ ...e-item-of-local-collection-mutate-later.js | 19 +++ ...iterator-of-immutable-collection.expect.md | 17 +-- ...-mutate-item-of-local-collection.expect.md | 55 +++++++ .../for-of-mutate-item-of-local-collection.js | 15 ++ ...onmutating-loop-local-collection.expect.md | 142 +++++++++++++++++ ...or-of-nonmutating-loop-local-collection.js | 31 ++++ .../packages/snap/src/SproutTodoFilter.ts | 1 - 24 files changed, 699 insertions(+), 76 deletions(-) create mode 100644 compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/error.invalid-mutate-props-via-for-of-iterator.expect.md create mode 100644 compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/error.invalid-mutate-props-via-for-of-iterator.js create mode 100644 compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/error.todo-for-of-capture-item-of-local-collection-mutate-later-value-initially-null.expect.md create mode 100644 compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/error.todo-for-of-capture-item-of-local-collection-mutate-later-value-initially-null.js create mode 100644 compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/for-of-capture-item-of-local-collection-mutate-later.expect.md create mode 100644 compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/for-of-capture-item-of-local-collection-mutate-later.js create mode 100644 compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/for-of-mutate-item-of-local-collection.expect.md create mode 100644 compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/for-of-mutate-item-of-local-collection.js create mode 100644 compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/for-of-nonmutating-loop-local-collection.expect.md create mode 100644 compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/for-of-nonmutating-loop-local-collection.js diff --git a/compiler/packages/babel-plugin-react-forget/src/HIR/BuildHIR.ts b/compiler/packages/babel-plugin-react-forget/src/HIR/BuildHIR.ts index cd95500667..8c039ebbf6 100644 --- a/compiler/packages/babel-plugin-react-forget/src/HIR/BuildHIR.ts +++ b/compiler/packages/babel-plugin-react-forget/src/HIR/BuildHIR.ts @@ -1006,6 +1006,7 @@ function lowerStatement( const stmt = stmtPath as NodePath; const continuationBlock = builder.reserve("block"); const initBlock = builder.reserve("loop"); + const testBlock = builder.reserve("loop"); const loopBlock = builder.enter("block", (_blockId) => { return builder.loop(label, initBlock.id, continuationBlock.id, () => { @@ -1028,6 +1029,7 @@ function lowerStatement( kind: "for-of", loc, init: initBlock.id, + test: testBlock.id, loop: loopBlock, fallthrough: continuationBlock.id, id: makeInstructionId(0), @@ -1040,6 +1042,22 @@ function lowerStatement( * right (Expression), so we synthesize a new InstrValue and assignment (potentially multiple * instructions when we handle other syntax like Patterns) */ + const iterator = lowerValueToTemporary(builder, { + kind: "GetIterator", + loc: value.loc, + collection: { ...value }, + }); + builder.terminateWithContinuation( + { + id: makeInstructionId(0), + kind: "goto", + block: testBlock.id, + variant: GotoVariant.Break, + loc: stmt.node.loc ?? GeneratedSource, + }, + testBlock + ); + const left = stmt.get("left"); const leftLoc = left.node.loc ?? GeneratedSource; let test: Place; @@ -1055,7 +1073,8 @@ function lowerStatement( const nextIterableOf = lowerValueToTemporary(builder, { kind: "NextIterableOf", loc: leftLoc, - value, + iterator: { ...iterator }, + collection: { ...value }, }); const assign = lowerAssignment( builder, diff --git a/compiler/packages/babel-plugin-react-forget/src/HIR/HIR.ts b/compiler/packages/babel-plugin-react-forget/src/HIR/HIR.ts index 95dddce76f..53f9424727 100644 --- a/compiler/packages/babel-plugin-react-forget/src/HIR/HIR.ts +++ b/compiler/packages/babel-plugin-react-forget/src/HIR/HIR.ts @@ -234,6 +234,7 @@ export type ReactiveForTerminal = { export type ReactiveForOfTerminal = { kind: "for-of"; init: ReactiveValue; + test: ReactiveValue; loop: ReactiveBlock; id: InstructionId; loc: SourceLocation; @@ -502,6 +503,7 @@ export type ForOfTerminal = { kind: "for-of"; loc: SourceLocation; init: BlockId; + test: BlockId; loop: BlockId; fallthrough: BlockId; id: InstructionId; @@ -958,12 +960,13 @@ export type InstructionValue = } | { kind: "GetIterator"; - value: Place; // the collection + collection: Place; // the collection loc: SourceLocation; } | { kind: "NextIterableOf"; - value: Place; // the iterator created with GetIterator + iterator: Place; // the iterator created with GetIterator + collection: Place; // the collection being iterated over (which may be an iterable or iterator) loc: SourceLocation; } | { @@ -1442,6 +1445,10 @@ export function isPrimitiveType(id: Identifier): boolean { return id.type.kind === "Primitive"; } +export function isArrayType(id: Identifier): boolean { + return id.type.kind === "Object" && id.type.shapeId === "BuiltInArray"; +} + export function isRefValueType(id: Identifier): boolean { return id.type.kind === "Object" && id.type.shapeId === "BuiltInRefValue"; } diff --git a/compiler/packages/babel-plugin-react-forget/src/HIR/PrintHIR.ts b/compiler/packages/babel-plugin-react-forget/src/HIR/PrintHIR.ts index fdec42ec73..9610aff30b 100644 --- a/compiler/packages/babel-plugin-react-forget/src/HIR/PrintHIR.ts +++ b/compiler/packages/babel-plugin-react-forget/src/HIR/PrintHIR.ts @@ -245,7 +245,7 @@ export function printTerminal(terminal: Terminal): Array | string { break; } case "for-of": { - value = `[${terminal.id}] ForOf init=bb${terminal.init} loop=bb${terminal.loop} fallthrough=bb${terminal.fallthrough}`; + value = `[${terminal.id}] ForOf init=bb${terminal.init} test=bb${terminal.test} loop=bb${terminal.loop} fallthrough=bb${terminal.fallthrough}`; break; } case "for-in": { @@ -610,11 +610,13 @@ export function printInstructionValue(instrValue: ReactiveValue): string { break; } case "GetIterator": { - value = `GetIterator ${printPlace(instrValue.value)}`; + value = `GetIterator collection=${printPlace(instrValue.collection)}`; break; } case "NextIterableOf": { - value = `NextIterableOf ${printPlace(instrValue.value)}`; + value = `NextIterableOf iterator=${printPlace( + instrValue.iterator + )} collection=${printPlace(instrValue.collection)}`; break; } case "NextPropertyOf": { diff --git a/compiler/packages/babel-plugin-react-forget/src/HIR/visitors.ts b/compiler/packages/babel-plugin-react-forget/src/HIR/visitors.ts index d3f89da16b..96c76b5939 100644 --- a/compiler/packages/babel-plugin-react-forget/src/HIR/visitors.ts +++ b/compiler/packages/babel-plugin-react-forget/src/HIR/visitors.ts @@ -208,9 +208,13 @@ export function* eachInstructionValueOperand( yield instrValue.value; break; } - case "GetIterator": + case "GetIterator": { + yield instrValue.collection; + break; + } case "NextIterableOf": { - yield instrValue.value; + yield instrValue.iterator; + yield instrValue.collection; break; } case "NextPropertyOf": { @@ -528,9 +532,13 @@ export function mapInstructionValueOperands( instrValue.value = fn(instrValue.value); break; } - case "GetIterator": + case "GetIterator": { + instrValue.collection = fn(instrValue.collection); + break; + } case "NextIterableOf": { - instrValue.value = fn(instrValue.value); + instrValue.iterator = fn(instrValue.iterator); + instrValue.collection = fn(instrValue.collection); break; } case "NextPropertyOf": { @@ -769,11 +777,13 @@ export function mapTerminalSuccessors( case "for-of": { const init = fn(terminal.init); const loop = fn(terminal.loop); + const test = fn(terminal.test); const fallthrough = fn(terminal.fallthrough); return { kind: "for-of", loc: terminal.loc, init, + test, loop, fallthrough, id: makeInstructionId(0), diff --git a/compiler/packages/babel-plugin-react-forget/src/Inference/InferReferenceEffects.ts b/compiler/packages/babel-plugin-react-forget/src/Inference/InferReferenceEffects.ts index 80b1fde823..5611e64223 100644 --- a/compiler/packages/babel-plugin-react-forget/src/Inference/InferReferenceEffects.ts +++ b/compiler/packages/babel-plugin-react-forget/src/Inference/InferReferenceEffects.ts @@ -26,6 +26,7 @@ import { Type, ValueKind, ValueReason, + isArrayType, isMutableEffect, isObjectType, } from "../HIR/HIR"; @@ -1811,27 +1812,78 @@ function inferBlock( continue; } case "GetIterator": { - effect = { kind: Effect.Capture, reason: ValueReason.Other }; + /** + * This instruction represents the step of retrieving an iterator from the collection + * in `for (... of )` syntax. We model two cases: + * + * 1. The collection is immutable or a known collection type (e.g. Array). In this case + * we infer that the iterator produced won't be the same as the collection itself. + * If the collection is an Array, this is because it will produce a native Array + * iterator. If the collection is already frozen, we assume it must be of some + * type that returns a separate iterator. In theory you could pass an Iterator + * as props to a component and then for..of over that in the component body, but + * this already violates React's rules so we assume you're not doing this. + * 2. The collection could be an Iterator itself, such that advancing the iterator + * (modeled with NextIterableOf) mutates the collection itself. + */ + const kind = state.kind(instrValue.collection).kind; + const isMutable = + kind === ValueKind.Mutable || kind === ValueKind.Context; + if (!isMutable || isArrayType(instrValue.collection.identifier)) { + // Case 1, assume iterator is a separate mutable object + effect = { + kind: Effect.Read, + reason: ValueReason.Other, + }; + valueKind = { + kind: ValueKind.Mutable, + reason: new Set([ValueReason.Other]), + context: new Set(), + }; + } else { + // Case 2, assume that the iterator could be the (mutable) collection itself + effect = { + kind: Effect.Capture, + reason: ValueReason.Other, + }; + valueKind = state.kind(instrValue.collection); + } lvalueEffect = Effect.Store; - valueKind = { - kind: ValueKind.Mutable, - reason: new Set([ValueReason.Other]), - context: new Set(), - }; break; } case "NextIterableOf": { - effect = { - kind: Effect.Capture, - reason: ValueReason.Other, - }; - lvalueEffect = Effect.Store; - valueKind = { - kind: ValueKind.Mutable, - reason: new Set([ValueReason.Other]), - context: new Set(), - }; - break; + /** + * This instruction represents advancing an iterator with .next(). We use a + * conditional mutate to model the two cases for GetIterator: + * - If the collection is a mutable iterator, we want to model the fact that + * advancing the iterator will mutate it + * - If the iterator may be different from the collection and the collection + * is frozen, we don't want to report a false positive "cannot mutate" error. + * + * ConditionallyMutate reflects this "mutate if mutable" semantic. + */ + state.referenceAndRecordEffects( + instrValue.iterator, + Effect.ConditionallyMutate, + ValueReason.Other, + functionEffects + ); + /** + * Regardless of the effect on the iterator, the *result* of advancing the iterator + * is to extract a value from the collection. We use a Capture effect to reflect this + * aliasing, and then initialize() the lvalue to the same kind as the colleciton to + * ensure that the item is mutable or frozen if the collection is mutable/frozen. + */ + state.referenceAndRecordEffects( + instrValue.collection, + Effect.Capture, + ValueReason.Other, + functionEffects + ); + state.initialize(instrValue, state.kind(instrValue.collection)); + state.define(instr.lvalue, instrValue); + instr.lvalue.effect = Effect.Store; + continue; } case "NextPropertyOf": { effect = { kind: Effect.Read, reason: ValueReason.Other }; diff --git a/compiler/packages/babel-plugin-react-forget/src/ReactiveScopes/BuildReactiveFunction.ts b/compiler/packages/babel-plugin-react-forget/src/ReactiveScopes/BuildReactiveFunction.ts index 994649429f..8218adf098 100644 --- a/compiler/packages/babel-plugin-react-forget/src/ReactiveScopes/BuildReactiveFunction.ts +++ b/compiler/packages/babel-plugin-react-forget/src/ReactiveScopes/BuildReactiveFunction.ts @@ -471,6 +471,31 @@ class Driver { }; } + const test = this.visitValueBlock(terminal.test, terminal.loc); + const testBlock = this.cx.ir.blocks.get(test.block)!; + let testValue = test.value; + if (testValue.kind === "SequenceExpression") { + const last = testBlock.instructions.at(-1)!; + testValue.instructions.push(last); + testValue.value = { + kind: "Primitive", + value: undefined, + loc: terminal.loc, + }; + } else { + testValue = { + kind: "SequenceExpression", + instructions: [testBlock.instructions.at(-1)!], + id: terminal.id, + loc: terminal.loc, + value: { + kind: "Primitive", + value: undefined, + loc: terminal.loc, + }, + }; + } + let loopBody: ReactiveBlock; if (loopId) { loopBody = this.traverseBlock(this.cx.ir.blocks.get(loopId)!); @@ -488,6 +513,7 @@ class Driver { kind: "for-of", loc: terminal.loc, init: initValue, + test: testValue, loop: loopBody, id: terminal.id, }, diff --git a/compiler/packages/babel-plugin-react-forget/src/ReactiveScopes/CodegenReactiveFunction.ts b/compiler/packages/babel-plugin-react-forget/src/ReactiveScopes/CodegenReactiveFunction.ts index 3f1030399c..5b56caa35d 100644 --- a/compiler/packages/babel-plugin-react-forget/src/ReactiveScopes/CodegenReactiveFunction.ts +++ b/compiler/packages/babel-plugin-react-forget/src/ReactiveScopes/CodegenReactiveFunction.ts @@ -650,17 +650,16 @@ function codegenTerminal( codegenBlock(cx, terminal.loop) ); } - case "for-in": - case "for-of": { + case "for-in": { CompilerError.invariant(terminal.init.kind === "SequenceExpression", { - reason: `Expected a sequence expression init for ForOf`, + reason: `Expected a sequence expression init for for..in`, description: `Got \`${terminal.init.kind}\` expression instead`, loc: terminal.init.loc, suggestions: null, }); if (terminal.init.instructions.length !== 2) { CompilerError.throwTodo({ - reason: "Support non-trivial ForOf inits", + reason: "Support non-trivial for..in inits", description: null, loc: terminal.init.loc, suggestions: null, @@ -704,14 +703,14 @@ function codegenTerminal( }); case InstructionKind.Catch: CompilerError.invariant(false, { - reason: "Unexpected catch variable as for-of collection", + reason: "Unexpected catch variable as for..in collection", description: null, loc: iterableItem.loc, suggestions: null, }); case InstructionKind.HoistedConst: CompilerError.invariant(false, { - reason: "Unexpected HoistedConst variable in for-of collection", + reason: "Unexpected HoistedConst variable in for..in collection", description: null, loc: iterableItem.loc, suggestions: null, @@ -722,31 +721,112 @@ function codegenTerminal( `Unhandled lvalue kind: ${iterableItem.value.lvalue.kind}` ); } - if (terminal.kind === "for-of") { - return t.forOfStatement( - /* - * Special handling here since we only want the VariableDeclarators without any inits - * This needs to be updated when we handle non-trivial ForOf inits - */ - createVariableDeclaration(iterableItem.value.loc, varDeclKind, [ - t.variableDeclarator(lval, null), - ]), - codegenInstructionValueToExpression(cx, iterableCollection.value), - codegenBlock(cx, terminal.loop) - ); - } else { - return t.forInStatement( - /* - * Special handling here since we only want the VariableDeclarators without any inits - * This needs to be updated when we handle non-trivial ForOf inits - */ - createVariableDeclaration(iterableItem.value.loc, varDeclKind, [ - t.variableDeclarator(lval, null), - ]), - codegenInstructionValueToExpression(cx, iterableCollection.value), - codegenBlock(cx, terminal.loop) - ); + return t.forInStatement( + /* + * Special handling here since we only want the VariableDeclarators without any inits + * This needs to be updated when we handle non-trivial ForOf inits + */ + createVariableDeclaration(iterableItem.value.loc, varDeclKind, [ + t.variableDeclarator(lval, null), + ]), + codegenInstructionValueToExpression(cx, iterableCollection.value), + codegenBlock(cx, terminal.loop) + ); + } + case "for-of": { + CompilerError.invariant( + terminal.init.kind === "SequenceExpression" && + terminal.init.instructions.length === 1 && + terminal.init.instructions[0].value.kind === "GetIterator", + { + reason: `Expected a single-expression sequence expression init for for..of`, + description: `Got \`${terminal.init.kind}\` expression instead`, + loc: terminal.init.loc, + suggestions: null, + } + ); + const iterableCollection = terminal.init.instructions[0].value; + + CompilerError.invariant(terminal.test.kind === "SequenceExpression", { + reason: `Expected a sequence expression test for for..of`, + description: `Got \`${terminal.init.kind}\` expression instead`, + loc: terminal.test.loc, + suggestions: null, + }); + if (terminal.test.instructions.length !== 2) { + CompilerError.throwTodo({ + reason: "Support non-trivial for..of inits", + description: null, + loc: terminal.init.loc, + suggestions: null, + }); } + const iterableItem = terminal.test.instructions[1]; + let lval: t.LVal; + switch (iterableItem.value.kind) { + case "StoreLocal": { + lval = codegenLValue(cx, iterableItem.value.lvalue.place); + break; + } + case "Destructure": { + lval = codegenLValue(cx, iterableItem.value.lvalue.pattern); + break; + } + default: + CompilerError.invariant(false, { + reason: `Expected a StoreLocal or Destructure to be assigned to the collection`, + description: `Found ${iterableItem.value.kind}`, + loc: iterableItem.value.loc, + suggestions: null, + }); + } + let varDeclKind: "const" | "let"; + switch (iterableItem.value.lvalue.kind) { + case InstructionKind.Const: + varDeclKind = "const" as const; + break; + case InstructionKind.Let: + varDeclKind = "let" as const; + break; + case InstructionKind.Reassign: + CompilerError.invariant(false, { + reason: + "Destructure should never be Reassign as it would be an Object/ArrayPattern", + description: null, + loc: iterableItem.loc, + suggestions: null, + }); + case InstructionKind.Catch: + CompilerError.invariant(false, { + reason: "Unexpected catch variable as for..of collection", + description: null, + loc: iterableItem.loc, + suggestions: null, + }); + case InstructionKind.HoistedConst: + CompilerError.invariant(false, { + reason: "Unexpected HoistedConst variable in for..of collection", + description: null, + loc: iterableItem.loc, + suggestions: null, + }); + default: + assertExhaustive( + iterableItem.value.lvalue.kind, + `Unhandled lvalue kind: ${iterableItem.value.lvalue.kind}` + ); + } + return t.forOfStatement( + /* + * Special handling here since we only want the VariableDeclarators without any inits + * This needs to be updated when we handle non-trivial ForOf inits + */ + createVariableDeclaration(iterableItem.value.loc, varDeclKind, [ + t.variableDeclarator(lval, null), + ]), + codegenInstructionValueToExpression(cx, iterableCollection), + codegenBlock(cx, terminal.loop) + ); } case "if": { const test = codegenPlaceToExpression(cx, terminal.test); @@ -1773,11 +1853,11 @@ function codegenInstructionValue( break; } case "GetIterator": { - value = codegenPlaceToExpression(cx, instrValue.value); + value = codegenPlaceToExpression(cx, instrValue.collection); break; } case "NextIterableOf": { - value = codegenPlaceToExpression(cx, instrValue.value); + value = codegenPlaceToExpression(cx, instrValue.iterator); break; } case "NextPropertyOf": { diff --git a/compiler/packages/babel-plugin-react-forget/src/ReactiveScopes/PrintReactiveFunction.ts b/compiler/packages/babel-plugin-react-forget/src/ReactiveScopes/PrintReactiveFunction.ts index ee878b1ff4..396592eb08 100644 --- a/compiler/packages/babel-plugin-react-forget/src/ReactiveScopes/PrintReactiveFunction.ts +++ b/compiler/packages/babel-plugin-react-forget/src/ReactiveScopes/PrintReactiveFunction.ts @@ -318,6 +318,8 @@ function writeTerminal(writer: Writer, terminal: ReactiveTerminal): void { writer.writeLine(`[${terminal.id}] for-of (`); writer.indented(() => { writeReactiveValue(writer, terminal.init); + writer.writeLine(";"); + writeReactiveValue(writer, terminal.test); }); writer.writeLine(") {"); writeReactiveInstructions(writer, terminal.loop); diff --git a/compiler/packages/babel-plugin-react-forget/src/ReactiveScopes/PruneNonEscapingScopes.ts b/compiler/packages/babel-plugin-react-forget/src/ReactiveScopes/PruneNonEscapingScopes.ts index bec0b616d8..94beb58100 100644 --- a/compiler/packages/babel-plugin-react-forget/src/ReactiveScopes/PruneNonEscapingScopes.ts +++ b/compiler/packages/babel-plugin-react-forget/src/ReactiveScopes/PruneNonEscapingScopes.ts @@ -474,9 +474,7 @@ function computeMemoizationInputs( }; } case "Await": - case "TypeCastExpression": - case "GetIterator": - case "NextIterableOf": { + case "TypeCastExpression": { return { // Indirection for the inner value, memoized if the value is lvalues: @@ -486,6 +484,26 @@ function computeMemoizationInputs( rvalues: [value.value], }; } + case "NextIterableOf": { + return { + // Indirection for the inner value, memoized if the value is + lvalues: + lvalue !== null + ? [{ place: lvalue, level: MemoizationLevel.Conditional }] + : [], + rvalues: [value.iterator, value.collection], + }; + } + case "GetIterator": { + return { + // Indirection for the inner value, memoized if the value is + lvalues: + lvalue !== null + ? [{ place: lvalue, level: MemoizationLevel.Conditional }] + : [], + rvalues: [value.collection], + }; + } case "LoadLocal": { return { // Indirection for the inner value, memoized if the value is diff --git a/compiler/packages/babel-plugin-react-forget/src/ReactiveScopes/visitors.ts b/compiler/packages/babel-plugin-react-forget/src/ReactiveScopes/visitors.ts index 616f09fb4f..2e2fd1b5d0 100644 --- a/compiler/packages/babel-plugin-react-forget/src/ReactiveScopes/visitors.ts +++ b/compiler/packages/babel-plugin-react-forget/src/ReactiveScopes/visitors.ts @@ -132,6 +132,7 @@ export class ReactiveFunctionVisitor { } case "for-of": { this.visitValue(terminal.id, terminal.init, state); + this.visitValue(terminal.id, terminal.test, state); this.visitBlock(terminal.loop, state); break; } @@ -492,6 +493,10 @@ export class ReactiveFunctionTransform< if (init.kind === "replace") { terminal.init = init.value; } + const test = this.transformValue(terminal.id, terminal.test, state); + if (test.kind === "replace") { + terminal.test = test.value; + } this.visitBlock(terminal.loop, state); break; } diff --git a/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/error.invalid-mutate-props-via-for-of-iterator.expect.md b/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/error.invalid-mutate-props-via-for-of-iterator.expect.md new file mode 100644 index 0000000000..d7942fc6a5 --- /dev/null +++ b/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/error.invalid-mutate-props-via-for-of-iterator.expect.md @@ -0,0 +1,29 @@ + +## Input + +```javascript +function Component(props) { + const items = []; + for (const x of props.items) { + x.modified = true; + items.push(x); + } + return items; +} + +``` + + +## Error + +``` + 2 | const items = []; + 3 | for (const x of props.items) { +> 4 | x.modified = true; + | ^ InvalidReact: Mutating component props or hook arguments is not allowed. Consider using a local variable instead (4:4) + 5 | items.push(x); + 6 | } + 7 | return items; +``` + + \ No newline at end of file diff --git a/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/error.invalid-mutate-props-via-for-of-iterator.js b/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/error.invalid-mutate-props-via-for-of-iterator.js new file mode 100644 index 0000000000..d7fd495192 --- /dev/null +++ b/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/error.invalid-mutate-props-via-for-of-iterator.js @@ -0,0 +1,8 @@ +function Component(props) { + const items = []; + for (const x of props.items) { + x.modified = true; + items.push(x); + } + return items; +} diff --git a/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/error.todo-for-in-loop-with-context-variable-iterator.expect.md b/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/error.todo-for-in-loop-with-context-variable-iterator.expect.md index ca19c86a86..09aa77345e 100644 --- a/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/error.todo-for-in-loop-with-context-variable-iterator.expect.md +++ b/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/error.todo-for-in-loop-with-context-variable-iterator.expect.md @@ -48,7 +48,7 @@ export const FIXTURE_ENTRYPOINT = { > 14 | ); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ > 15 | } - | ^^^^ Todo: Support non-trivial ForOf inits (8:15) + | ^^^^ Todo: Support non-trivial for..in inits (8:15) 16 | return
{items}
; 17 | } 18 | diff --git a/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/error.todo-for-of-capture-item-of-local-collection-mutate-later-value-initially-null.expect.md b/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/error.todo-for-of-capture-item-of-local-collection-mutate-later-value-initially-null.expect.md new file mode 100644 index 0000000000..3c0eea1666 --- /dev/null +++ b/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/error.todo-for-of-capture-item-of-local-collection-mutate-later-value-initially-null.expect.md @@ -0,0 +1,34 @@ + +## Input + +```javascript +import { makeObject_Primitives } from "shared-runtime"; + +function Component(props) { + let lastItem = null; // we reject this code bc `lastItem` could be null and you can't mutate null + const items = [makeObject_Primitives(), makeObject_Primitives()]; + for (const x of items) { + lastItem = x; + } + if (lastItem != null) { + lastItem.mutated = true; + } + return items; +} + +``` + + +## Error + +``` + 8 | } + 9 | if (lastItem != null) { +> 10 | lastItem.mutated = true; + | ^^^^^^^^ InvalidReact: This mutates a variable that React considers immutable (10:10) + 11 | } + 12 | return items; + 13 | } +``` + + \ No newline at end of file diff --git a/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/error.todo-for-of-capture-item-of-local-collection-mutate-later-value-initially-null.js b/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/error.todo-for-of-capture-item-of-local-collection-mutate-later-value-initially-null.js new file mode 100644 index 0000000000..3695bcdb2c --- /dev/null +++ b/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/error.todo-for-of-capture-item-of-local-collection-mutate-later-value-initially-null.js @@ -0,0 +1,13 @@ +import { makeObject_Primitives } from "shared-runtime"; + +function Component(props) { + let lastItem = null; // we reject this code bc `lastItem` could be null and you can't mutate null + const items = [makeObject_Primitives(), makeObject_Primitives()]; + for (const x of items) { + lastItem = x; + } + if (lastItem != null) { + lastItem.mutated = true; + } + return items; +} diff --git a/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/error.todo-for-of-loop-with-context-variable-iterator.expect.md b/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/error.todo-for-of-loop-with-context-variable-iterator.expect.md index fc9c5a9790..05b17b3137 100644 --- a/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/error.todo-for-of-loop-with-context-variable-iterator.expect.md +++ b/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/error.todo-for-of-loop-with-context-variable-iterator.expect.md @@ -48,7 +48,7 @@ export const FIXTURE_ENTRYPOINT = { > 14 | ); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ > 15 | } - | ^^^^ Todo: Support non-trivial ForOf inits (8:15) + | ^^^^ Todo: Support non-trivial for..of inits (8:15) 16 | return
{items}
; 17 | } 18 | diff --git a/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/for-of-capture-item-of-local-collection-mutate-later.expect.md b/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/for-of-capture-item-of-local-collection-mutate-later.expect.md new file mode 100644 index 0000000000..39f3608bca --- /dev/null +++ b/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/for-of-capture-item-of-local-collection-mutate-later.expect.md @@ -0,0 +1,62 @@ + +## Input + +```javascript +import { makeObject_Primitives } from "shared-runtime"; + +function Component(props) { + let lastItem = {}; + const items = [makeObject_Primitives(), makeObject_Primitives()]; + for (const x of items) { + lastItem = x; + } + if (lastItem != null) { + lastItem.a += 1; + } + return items; +} + +export const FIXTURE_ENTRYPOINT = { + fn: Component, + params: [{}], + sequentialRenders: [{}, {}], +}; + +``` + +## Code + +```javascript +import { unstable_useMemoCache as useMemoCache } from "react"; +import { makeObject_Primitives } from "shared-runtime"; + +function Component(props) { + const $ = useMemoCache(1); + let items; + if ($[0] === Symbol.for("react.memo_cache_sentinel")) { + let lastItem = {}; + items = [makeObject_Primitives(), makeObject_Primitives()]; + for (const x of items) { + lastItem = x; + } + if (lastItem != null) { + lastItem.a = lastItem.a + 1; + } + $[0] = items; + } else { + items = $[0]; + } + return items; +} + +export const FIXTURE_ENTRYPOINT = { + fn: Component, + params: [{}], + sequentialRenders: [{}, {}], +}; + +``` + +### Eval output +(kind: ok) [{"a":0,"b":"value1","c":true},{"a":1,"b":"value1","c":true}] +[{"a":0,"b":"value1","c":true},{"a":1,"b":"value1","c":true}] \ No newline at end of file diff --git a/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/for-of-capture-item-of-local-collection-mutate-later.js b/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/for-of-capture-item-of-local-collection-mutate-later.js new file mode 100644 index 0000000000..3a4a92a661 --- /dev/null +++ b/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/for-of-capture-item-of-local-collection-mutate-later.js @@ -0,0 +1,19 @@ +import { makeObject_Primitives } from "shared-runtime"; + +function Component(props) { + let lastItem = {}; + const items = [makeObject_Primitives(), makeObject_Primitives()]; + for (const x of items) { + lastItem = x; + } + if (lastItem != null) { + lastItem.a += 1; + } + return items; +} + +export const FIXTURE_ENTRYPOINT = { + fn: Component, + params: [{}], + sequentialRenders: [{}, {}], +}; diff --git a/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/for-of-iterator-of-immutable-collection.expect.md b/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/for-of-iterator-of-immutable-collection.expect.md index 1f89b0aa8e..401206d725 100644 --- a/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/for-of-iterator-of-immutable-collection.expect.md +++ b/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/for-of-iterator-of-immutable-collection.expect.md @@ -37,20 +37,12 @@ export const FIXTURE_ENTRYPOINT = { ```javascript import { unstable_useMemoCache as useMemoCache } from "react"; function Router(t0) { - const $ = useMemoCache(5); + const $ = useMemoCache(3); const { title, mapping } = t0; let array; if ($[0] !== mapping || $[1] !== title) { array = []; - let t1; - if ($[3] !== mapping) { - t1 = mapping.values(); - $[3] = mapping; - $[4] = t1; - } else { - t1 = $[4]; - } - for (const entry of t1) { + for (const entry of mapping.values()) { array.push([title, entry]); } $[0] = mapping; @@ -83,4 +75,7 @@ export const FIXTURE_ENTRYPOINT = { }; ``` - \ No newline at end of file + +### Eval output +(kind: ok) [["Foo","/about"],["Foo","/contact"]] +[["Bar","/about"],["Bar","/contact"]] \ No newline at end of file diff --git a/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/for-of-mutate-item-of-local-collection.expect.md b/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/for-of-mutate-item-of-local-collection.expect.md new file mode 100644 index 0000000000..b11cc7c621 --- /dev/null +++ b/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/for-of-mutate-item-of-local-collection.expect.md @@ -0,0 +1,55 @@ + +## Input + +```javascript +import { makeObject_Primitives } from "shared-runtime"; + +function Component(props) { + const items = [makeObject_Primitives(), makeObject_Primitives()]; + for (const x of items) { + x.a += 1; + } + return items; +} + +export const FIXTURE_ENTRYPOINT = { + fn: Component, + params: [{}], + sequentialRenders: [{}, {}, {}], +}; + +``` + +## Code + +```javascript +import { unstable_useMemoCache as useMemoCache } from "react"; +import { makeObject_Primitives } from "shared-runtime"; + +function Component(props) { + const $ = useMemoCache(1); + let items; + if ($[0] === Symbol.for("react.memo_cache_sentinel")) { + items = [makeObject_Primitives(), makeObject_Primitives()]; + for (const x of items) { + x.a = x.a + 1; + } + $[0] = items; + } else { + items = $[0]; + } + return items; +} + +export const FIXTURE_ENTRYPOINT = { + fn: Component, + params: [{}], + sequentialRenders: [{}, {}, {}], +}; + +``` + +### Eval output +(kind: ok) [{"a":1,"b":"value1","c":true},{"a":1,"b":"value1","c":true}] +[{"a":1,"b":"value1","c":true},{"a":1,"b":"value1","c":true}] +[{"a":1,"b":"value1","c":true},{"a":1,"b":"value1","c":true}] \ No newline at end of file diff --git a/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/for-of-mutate-item-of-local-collection.js b/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/for-of-mutate-item-of-local-collection.js new file mode 100644 index 0000000000..c065645691 --- /dev/null +++ b/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/for-of-mutate-item-of-local-collection.js @@ -0,0 +1,15 @@ +import { makeObject_Primitives } from "shared-runtime"; + +function Component(props) { + const items = [makeObject_Primitives(), makeObject_Primitives()]; + for (const x of items) { + x.a += 1; + } + return items; +} + +export const FIXTURE_ENTRYPOINT = { + fn: Component, + params: [{}], + sequentialRenders: [{}, {}, {}], +}; diff --git a/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/for-of-nonmutating-loop-local-collection.expect.md b/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/for-of-nonmutating-loop-local-collection.expect.md new file mode 100644 index 0000000000..e52a3e31c8 --- /dev/null +++ b/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/for-of-nonmutating-loop-local-collection.expect.md @@ -0,0 +1,142 @@ + +## Input + +```javascript +import { useMemo } from "react"; +import { ValidateMemoization } from "shared-runtime"; + +function Component({ a, b }) { + const x = useMemo(() => { + return [a]; + }, [a]); + const y = useMemo(() => { + const items = [b]; + for (const i of x) { + items.push(i); + } + return items; + }, [x, b]); + return ( + <> + + + + ); +} + +export const FIXTURE_ENTRYPOINT = { + fn: Component, + params: [{ a: 0, b: 0 }], + sequentialRenders: [ + { a: 1, b: 0 }, + { a: 1, b: 1 }, + { a: 0, b: 1 }, + ], +}; + +``` + +## Code + +```javascript +import { useMemo, unstable_useMemoCache as useMemoCache } from "react"; +import { ValidateMemoization } from "shared-runtime"; + +function Component(t0) { + const $ = useMemoCache(19); + const { a, b } = t0; + let t1; + let t2; + if ($[0] !== a) { + t2 = [a]; + $[0] = a; + $[1] = t2; + } else { + t2 = $[1]; + } + t1 = t2; + const x = t1; + let t3; + let items; + if ($[2] !== b || $[3] !== x) { + items = [b]; + for (const i of x) { + items.push(i); + } + $[2] = b; + $[3] = x; + $[4] = items; + } else { + items = $[4]; + } + + t3 = items; + const y = t3; + let t4; + if ($[5] !== a) { + t4 = [a]; + $[5] = a; + $[6] = t4; + } else { + t4 = $[6]; + } + let t5; + if ($[7] !== t4 || $[8] !== x) { + t5 = ; + $[7] = t4; + $[8] = x; + $[9] = t5; + } else { + t5 = $[9]; + } + let t6; + if ($[10] !== x || $[11] !== b) { + t6 = [x, b]; + $[10] = x; + $[11] = b; + $[12] = t6; + } else { + t6 = $[12]; + } + let t7; + if ($[13] !== t6 || $[14] !== y) { + t7 = ; + $[13] = t6; + $[14] = y; + $[15] = t7; + } else { + t7 = $[15]; + } + let t8; + if ($[16] !== t5 || $[17] !== t7) { + t8 = ( + <> + {t5} + {t7} + + ); + $[16] = t5; + $[17] = t7; + $[18] = t8; + } else { + t8 = $[18]; + } + return t8; +} + +export const FIXTURE_ENTRYPOINT = { + fn: Component, + params: [{ a: 0, b: 0 }], + sequentialRenders: [ + { a: 1, b: 0 }, + { a: 1, b: 1 }, + { a: 0, b: 1 }, + ], +}; + +``` + +### Eval output +(kind: ok)
{"inputs":[1],"output":[1]}
{"inputs":[[1],0],"output":[0,1]}
+
{"inputs":[1],"output":[1]}
{"inputs":[[1],1],"output":[1,1]}
+
{"inputs":[0],"output":[0]}
{"inputs":[[0],1],"output":[1,0]}
\ No newline at end of file diff --git a/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/for-of-nonmutating-loop-local-collection.js b/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/for-of-nonmutating-loop-local-collection.js new file mode 100644 index 0000000000..0ac757aab8 --- /dev/null +++ b/compiler/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/for-of-nonmutating-loop-local-collection.js @@ -0,0 +1,31 @@ +import { useMemo } from "react"; +import { ValidateMemoization } from "shared-runtime"; + +function Component({ a, b }) { + const x = useMemo(() => { + return [a]; + }, [a]); + const y = useMemo(() => { + const items = [b]; + for (const i of x) { + items.push(i); + } + return items; + }, [x, b]); + return ( + <> + + + + ); +} + +export const FIXTURE_ENTRYPOINT = { + fn: Component, + params: [{ a: 0, b: 0 }], + sequentialRenders: [ + { a: 1, b: 0 }, + { a: 1, b: 1 }, + { a: 0, b: 1 }, + ], +}; diff --git a/compiler/packages/snap/src/SproutTodoFilter.ts b/compiler/packages/snap/src/SproutTodoFilter.ts index 0d67948bc2..7a9d8c7781 100644 --- a/compiler/packages/snap/src/SproutTodoFilter.ts +++ b/compiler/packages/snap/src/SproutTodoFilter.ts @@ -489,7 +489,6 @@ const skipFilter = new Set([ // bugs "bug-invalid-reactivity-value-block", - "for-of-iterator-of-immutable-collection", // 'react-forget-runtime' not yet supported "flag-enable-emit-hook-guards",