[λ] Parse and codegen arrow function exprs

This commit is contained in:
Sathya Gunasekaran
2023-01-23 17:39:37 -05:00
parent 3ba90a7f9c
commit ee3a88f20f
6 changed files with 64 additions and 8 deletions
+10 -5
View File
@@ -1334,16 +1334,21 @@ function lowerExpression(
loc: exprLoc,
};
}
case "ArrowFunctionExpression":
case "FunctionExpression": {
const expr = exprPath as NodePath<t.FunctionExpression>;
const name: string | null = expr.get("id")?.node?.name ?? null;
const expr = exprPath as NodePath<
t.FunctionExpression | t.ArrowFunctionExpression
>;
let name: string | null = null;
if (expr.isFunctionExpression()) {
name = expr.get("id")?.node?.name ?? null;
}
const componentScope: Scope = expr.scope.parent.getFunctionParent()!;
const dependencies: Array<Place> = gatherCapturedDeps(
builder,
expr,
componentScope
);
const body = expr.get("body").node;
const lowering = lower(expr);
let loweredFunc: HIRFunction;
if (lowering.isErr()) {
@@ -1375,11 +1380,11 @@ function lowerExpression(
: {
kind: "FunctionExpression",
name,
body,
params,
loweredFunc,
dependencies,
mutatedDeps: [],
expr: expr.node,
loc: exprLoc,
};
}
@@ -1901,7 +1906,7 @@ function captureScopes({ from, to }: { from: Scope; to: Scope }): Set<Scope> {
function gatherCapturedDeps(
builder: HIRBuilder,
fn: NodePath<t.FunctionExpression>,
fn: NodePath<t.FunctionExpression | t.ArrowFunctionExpression>,
componentScope: Scope
): Array<Place> {
const captured: Set<Place> = new Set();
+1 -1
View File
@@ -407,7 +407,7 @@ export type InstructionData =
// source of truth.
mutatedDeps: Array<Place>;
loweredFunc: HIRFunction;
body: t.BlockStatement;
expr: t.ArrowFunctionExpression | t.FunctionExpression;
}
/**
+1 -1
View File
@@ -312,7 +312,7 @@ export function printInstructionValue(instrValue: InstructionValue): string {
}
case "FunctionExpression": {
const params = instrValue.params.join(",");
const body = generate(instrValue.body).code;
const body = generate(instrValue.expr).code;
const deps = instrValue.dependencies
.map((i) => printIdentifier(i.identifier))
.join(",");
@@ -662,7 +662,7 @@ function codegenInstructionValue(
const id =
instrValue.name !== null ? t.identifier(instrValue.name) : null;
const params = instrValue.params.map((p) => t.identifier(p));
value = t.functionExpression(id, params, instrValue.body);
value = instrValue.expr;
break;
}
default: {
@@ -0,0 +1,44 @@
## Input
```javascript
function component(a) {
let z = { a };
let x = () => {
z;
};
return x;
}
```
## Code
```javascript
function component(a) {
const $ = React.useMemoCache();
const c_0 = $[0] !== a;
let z;
if (c_0) {
z = { a: a };
$[0] = a;
$[1] = z;
} else {
z = $[1];
}
const c_2 = $[2] !== z;
let x;
if (c_2) {
x = () => {
z;
};
$[2] = z;
$[3] = x;
} else {
x = $[3];
}
return x;
}
```
@@ -0,0 +1,7 @@
function component(a) {
let z = { a };
let x = () => {
z;
};
return x;
}