Skip to content
This repository has been archived by the owner on Oct 9, 2024. It is now read-only.

Commit

Permalink
feat: Alias analysis problem
Browse files Browse the repository at this point in the history
  • Loading branch information
mohebifar committed Mar 2, 2024
1 parent 04a98ee commit c22c393
Show file tree
Hide file tree
Showing 12 changed files with 547 additions and 15 deletions.
6 changes: 6 additions & 0 deletions .changeset/metal-glasses-argue.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@react-unforget/compiler": minor
"@react-unforget/babel-plugin": minor
---

Alias analysis problem
67 changes: 67 additions & 0 deletions apps/docs/pages/examples/alias-analysis-problem.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { DynamicLiveCodeSandpack } from "@components/DynamicLiveCodeSandpack";

### Alias Analysis Problem

In this great talk about React Forget, [Sathya Gunasekaran](https://twitter.com/_gsathya) talks about the problem of alias analysis in making a compiler for React.

The following examples show how React Unforget can handle such cases that requires alias analysis.

The first example, is the same code snippet that Sathya shows in his keynote:

<DynamicLiveCodeSandpack previewClassName="h-44">
{`import { useState } from "react";
function Comp({ a, b }) {
const x = [];
x.push(a);
const y = x;
y.push(b);
return <div>n: {x.join(",")}</div>;
}
export default function App() {
const [state, setState] = useState(1);
return (
<div>
{/* We use a constant value for a, but change b */}
<Comp a={1} b={state} />
<button onClick={() => setState((p) => p + 1)}>click</button>
</div>
);
}
`}

</DynamicLiveCodeSandpack>

The second example is based on this example provided by Joe Savona in [this tweet](https://twitter.com/en_JS/status/1763621588791116241):

<DynamicLiveCodeSandpack previewClassName="h-44">
{`import { useState } from "react";
export default function CounterWithMutationTracking() {
const [state, setState] = useState(0);
let x = [];
const z = [];
let y = state % 2 === 0 ? x : z;
y.push(state);
return (
<div>
<button onClick={() => setState(state + 1)}>Increment</button>
{y[0]}
<br />
x: {JSON.stringify(x)}
<br />
y: {JSON.stringify(y)}
</div>
);
}
`}

</DynamicLiveCodeSandpack>
28 changes: 27 additions & 1 deletion packages/compiler/src/classes/Component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,32 @@ export class Component {
});
}

findDependents(componentVariableToFindDependentsFor: ComponentVariable) {
const dependents = new Set<ComponentMutableSegment>();

const addDepdendentsToSet = (segment: ComponentMutableSegment) => {
if (
[...segment.getDependencies().values()].some(
(dependency) =>
dependency.componentVariable ===
componentVariableToFindDependentsFor
)
) {
dependents.add(segment);
}
};

for (const [, componentVariable] of this.componentVariables) {
addDepdendentsToSet(componentVariable);
}

for (const [, runnableSegment] of this.runnableSegments) {
addDepdendentsToSet(runnableSegment);
}

return dependents;
}

addComponentVariable(binding: Binding) {
if (!this.isBindingInComponentScope(binding)) {
return;
Expand Down Expand Up @@ -183,7 +209,7 @@ export class Component {
return getFunctionParent(path) === this.path;
}

getRootComponentVariables() {
getComponentVariables() {
return [...this.componentVariables.values()].filter(
(componentVariable) => !componentVariable.hasDependencies()
);
Expand Down
17 changes: 17 additions & 0 deletions packages/compiler/src/classes/ComponentMutableSegment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,7 @@ export abstract class ComponentMutableSegment {

getDependenciesForTransformation() {
const dependencies = new Set(this.getDependencies());
const visited = new Set<ComponentSegmentDependency>();

dependencies.forEach((dependency) => {
if (!this.dependencies.has(dependency)) {
Expand All @@ -285,6 +286,22 @@ export abstract class ComponentMutableSegment {
).forEach((dependency) => {
dependencies.add(dependency);
});

this.component.findDependents(this).forEach((dependent) => {
const mutationDependencies =
dependent.isComponentVariable() &&
dependent.getMutationDependencies();
if (mutationDependencies) {
for (const dependencyOfMutation of mutationDependencies) {
if (visited.has(dependencyOfMutation)) {
continue;
}
if (dependencyOfMutation.componentVariable !== this) {
dependencies.add(dependencyOfMutation);
}
}
}
});
}

return dependencies;
Expand Down
9 changes: 8 additions & 1 deletion packages/compiler/src/classes/ComponentRunnableSegment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,8 +180,15 @@ export class ComponentRunnableSegment extends ComponentMutableSegment {
const isParentRoot =
this.parent?.isComponentRunnableSegment() && this.parent.isRoot();
const componentScope = this.component.path.scope;
let shouldScanForDependencies = isParentRoot && this.hasHookCall();

if (isParentRoot && this.hasHookCall()) {
if (!shouldScanForDependencies) {
shouldScanForDependencies = [
...this.component.getComponentVariables(),
].some((s) => s.isMutatedBy(this));
}

if (shouldScanForDependencies) {
const allBindingsOfComponent = Object.values(
componentScope.getAllBindings()
).filter((binding) => binding.scope === componentScope);
Expand Down
11 changes: 11 additions & 0 deletions packages/compiler/src/classes/ComponentVariable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,16 @@ export class ComponentVariable extends ComponentMutableSegment {
return isForStatementInit(this.path);
}

isMutatedBy(runnableSegment: ComponentRunnableSegment) {
for (const runnableItem of this.runnableSegmentsMutatingThis) {
if (runnableItem === runnableSegment) {
return true;
}
}

return false;
}

getMutationDependencies(visited = new Set<ComponentSegmentDependency>()) {
const mutatingDependencies = new Set<ComponentSegmentDependency>();
this.runnableSegmentsMutatingThis.forEach((runnableSegment) => {
Expand Down Expand Up @@ -302,6 +312,7 @@ export class ComponentVariable extends ComponentMutableSegment {

if (mutatingExpressions) {
this.runnableSegmentsMutatingThis.add(dependent);
dependent.computeDependencyGraph();
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ describe.skip("ComponentVariable", () => {
const [component] = parseCodeAndRun("fixture_2");
component.computeComponentSegments();

const rootComponentVariables = component.getRootComponentVariables();
const rootComponentVariables = component.getComponentVariables();

expect(
rootComponentVariables.map((v) => v.binding.identifier.name)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { loadFixture, transformWithStandalone } from "~/utils/testing";

describe("Component fixtures", () => {
describe("applyModification", () => {
it.each(Array.from({ length: 10 }, (_, i) => `fixture_${i + 1}`))(
it.each(Array.from({ length: 13 }, (_, i) => `fixture_${i + 1}`))(
"%s",
(fixtureName) => {
const code = transformWithStandalone(loadFixture(fixtureName));
Expand Down
Loading

0 comments on commit c22c393

Please sign in to comment.