Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ export function addImportsToProgram(
programContext: ProgramContext,
): void {
const existingImports = getExistingImports(path);
const stmts: Array<t.ImportDeclaration> = [];
const stmts: Array<t.ImportDeclaration | t.VariableDeclaration> = [];
const sortedModules = [...programContext.imports.entries()].sort(([a], [b]) =>
a.localeCompare(b),
);
Expand Down Expand Up @@ -303,9 +303,29 @@ export function addImportsToProgram(
if (maybeExistingImports != null) {
maybeExistingImports.pushContainer('specifiers', importSpecifiers);
} else {
stmts.push(
t.importDeclaration(importSpecifiers, t.stringLiteral(moduleName)),
);
if (path.node.sourceType === 'module') {
stmts.push(
t.importDeclaration(importSpecifiers, t.stringLiteral(moduleName)),
);
} else {
stmts.push(
t.variableDeclaration('const', [
t.variableDeclarator(
t.objectPattern(
sortedImport.map(specifier => {
return t.objectProperty(
t.identifier(specifier.imported),
t.identifier(specifier.name),
);
}),
),
t.callExpression(t.identifier('require'), [
t.stringLiteral(moduleName),
]),
),
]),
);
}
}
}
path.unshiftContainer('body', stmts);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export function nameAnonymousFunctions(fn: HIRFunction): void {
const parentName = fn.id;
const functions = nameAnonymousFunctionsImpl(fn);
function visit(node: Node, prefix: string): void {
if (node.generatedName != null) {
if (node.generatedName != null && node.fn.nameHint == null) {
/**
* Note that we don't generate a name for functions that already had one,
* so we'll only add the prefix to anonymous functions regardless of
Expand Down Expand Up @@ -70,6 +70,10 @@ function nameAnonymousFunctionsImpl(fn: HIRFunction): Array<Node> {
if (name != null && name.kind === 'named') {
names.set(lvalue.identifier.id, name.value);
}
const func = functions.get(value.place.identifier.id);
if (func != null) {
functions.set(lvalue.identifier.id, func);
}
break;
}
case 'PropertyLoad': {
Expand Down Expand Up @@ -106,6 +110,7 @@ function nameAnonymousFunctionsImpl(fn: HIRFunction): Array<Node> {
const variableName = value.lvalue.place.identifier.name;
if (
node != null &&
node.generatedName == null &&
variableName != null &&
variableName.kind === 'named'
) {
Expand Down Expand Up @@ -137,7 +142,7 @@ function nameAnonymousFunctionsImpl(fn: HIRFunction): Array<Node> {
continue;
}
const node = functions.get(arg.identifier.id);
if (node != null) {
if (node != null && node.generatedName == null) {
const generatedName =
fnArgCount > 1 ? `${calleeName}(arg${i})` : `${calleeName}()`;
node.generatedName = generatedName;
Expand All @@ -152,7 +157,7 @@ function nameAnonymousFunctionsImpl(fn: HIRFunction): Array<Node> {
continue;
}
const node = functions.get(attr.place.identifier.id);
if (node != null) {
if (node != null && node.generatedName == null) {
const elementName =
value.tag.kind === 'BuiltinTag'
? value.tag.name
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,19 @@
```javascript
// @enableNameAnonymousFunctions

import {useEffect} from 'react';
import {useCallback, useEffect} from 'react';
import {identity, Stringify, useIdentity} from 'shared-runtime';
import * as SharedRuntime from 'shared-runtime';

function Component(props) {
function named() {
const inner = () => props.named;
return inner();
const innerIdentity = identity(() => props.named);
return inner(innerIdentity());
}
const callback = useCallback(() => {
return 'ok';
}, []);
const namedVariable = function () {
return props.namedVariable;
};
Expand All @@ -30,6 +34,7 @@ function Component(props) {
return (
<>
{named()}
{callback()}
{namedVariable()}
{methodCall()}
{call()}
Expand Down Expand Up @@ -63,7 +68,7 @@ export const TODO_FIXTURE_ENTRYPOINT = {
```javascript
import { c as _c } from "react/compiler-runtime"; // @enableNameAnonymousFunctions

import { useEffect } from "react";
import { useCallback, useEffect } from "react";
import { identity, Stringify, useIdentity } from "shared-runtime";
import * as SharedRuntime from "shared-runtime";

Expand All @@ -75,14 +80,21 @@ function Component(props) {
const inner = { "Component[named > inner]": () => props.named }[
"Component[named > inner]"
];
return inner();
const innerIdentity = identity(
{ "Component[named > identity()]": () => props.named }[
"Component[named > identity()]"
],
);
return inner(innerIdentity());
};
$[0] = props.named;
$[1] = t0;
} else {
t0 = $[1];
}
const named = t0;

const callback = _ComponentCallback;
let t1;
if ($[2] !== props.namedVariable) {
t1 = {
Expand Down Expand Up @@ -197,57 +209,62 @@ function Component(props) {
} else {
t9 = $[18];
}
let t10;
const t10 = callback();
let t11;
if ($[19] !== namedVariable) {
t10 = namedVariable();
t11 = namedVariable();
$[19] = namedVariable;
$[20] = t10;
$[20] = t11;
} else {
t10 = $[20];
t11 = $[20];
}
const t11 = methodCall();
const t12 = call();
let t13;
const t12 = methodCall();
const t13 = call();
let t14;
if ($[21] !== hookArgument) {
t13 = hookArgument();
t14 = hookArgument();
$[21] = hookArgument;
$[22] = t13;
$[22] = t14;
} else {
t13 = $[22];
t14 = $[22];
}
let t14;
let t15;
if (
$[23] !== builtinElementAttr ||
$[24] !== namedElementAttr ||
$[25] !== t10 ||
$[26] !== t11 ||
$[27] !== t12 ||
$[28] !== t13 ||
$[25] !== t11 ||
$[26] !== t12 ||
$[27] !== t13 ||
$[28] !== t14 ||
$[29] !== t9
) {
t14 = (
t15 = (
<>
{t9}
{t10}
{t11}
{t12}
{t13}
{builtinElementAttr}
{namedElementAttr}
{t13}
{t14}
</>
);
$[23] = builtinElementAttr;
$[24] = namedElementAttr;
$[25] = t10;
$[26] = t11;
$[27] = t12;
$[28] = t13;
$[25] = t11;
$[26] = t12;
$[27] = t13;
$[28] = t14;
$[29] = t9;
$[30] = t14;
$[30] = t15;
} else {
t14 = $[30];
t15 = $[30];
}
return t14;
return t15;
}
function _ComponentCallback() {
return "ok";
}

export const TODO_FIXTURE_ENTRYPOINT = {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
// @enableNameAnonymousFunctions

import {useEffect} from 'react';
import {useCallback, useEffect} from 'react';
import {identity, Stringify, useIdentity} from 'shared-runtime';
import * as SharedRuntime from 'shared-runtime';

function Component(props) {
function named() {
const inner = () => props.named;
return inner();
const innerIdentity = identity(() => props.named);
return inner(innerIdentity());
}
const callback = useCallback(() => {
return 'ok';
}, []);
const namedVariable = function () {
return props.namedVariable;
};
Expand All @@ -26,6 +30,7 @@ function Component(props) {
return (
<>
{named()}
{callback()}
{namedVariable()}
{methodCall()}
{call()}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@

## Input

```javascript
// @script
const React = require('react');

function Component(props) {
return <div>{props.name}</div>;
}

// To work with snap evaluator
exports = {
FIXTURE_ENTRYPOINT: {
fn: Component,
params: [{name: 'React Compiler'}],
},
};

```

## Code

```javascript
const { c: _c } = require("react/compiler-runtime"); // @script
const React = require("react");

function Component(props) {
const $ = _c(2);
let t0;
if ($[0] !== props.name) {
t0 = <div>{props.name}</div>;
$[0] = props.name;
$[1] = t0;
} else {
t0 = $[1];
}
return t0;
}

// To work with snap evaluator
exports = {
FIXTURE_ENTRYPOINT: {
fn: Component,
params: [{ name: "React Compiler" }],
},
};

```

### Eval output
(kind: ok) <div>React Compiler</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// @script
const React = require('react');

function Component(props) {
return <div>{props.name}</div>;
}

// To work with snap evaluator
exports = {
FIXTURE_ENTRYPOINT: {
fn: Component,
params: [{name: 'React Compiler'}],
},
};
13 changes: 10 additions & 3 deletions compiler/packages/snap/src/compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,15 @@ import prettier from 'prettier';
import SproutTodoFilter from './SproutTodoFilter';
import {isExpectError} from './fixture-utils';
import {makeSharedRuntimeTypeProvider} from './sprout/shared-runtime-type-provider';

export function parseLanguage(source: string): 'flow' | 'typescript' {
return source.indexOf('@flow') !== -1 ? 'flow' : 'typescript';
}

export function parseSourceType(source: string): 'script' | 'module' {
return source.indexOf('@script') !== -1 ? 'script' : 'module';
}

/**
* Parse react compiler plugin + environment options from test fixture. Note
* that although this primarily uses `Environment:parseConfigPragma`, it also
Expand Down Expand Up @@ -98,21 +103,22 @@ export function parseInput(
input: string,
filename: string,
language: 'flow' | 'typescript',
sourceType: 'module' | 'script',
): BabelCore.types.File {
// Extract the first line to quickly check for custom test directives
if (language === 'flow') {
return HermesParser.parse(input, {
babel: true,
flow: 'all',
sourceFilename: filename,
sourceType: 'module',
sourceType,
enableExperimentalComponentSyntax: true,
});
} else {
return BabelParser.parse(input, {
sourceFilename: filename,
plugins: ['typescript', 'jsx'],
sourceType: 'module',
sourceType,
});
}
}
Expand Down Expand Up @@ -221,11 +227,12 @@ export async function transformFixtureInput(
const firstLine = input.substring(0, input.indexOf('\n'));

const language = parseLanguage(firstLine);
const sourceType = parseSourceType(firstLine);
// Preserve file extension as it determines typescript's babel transform
// mode (e.g. stripping types, parsing rules for brackets)
const filename =
path.basename(fixturePath) + (language === 'typescript' ? '.ts' : '');
const inputAst = parseInput(input, filename, language);
const inputAst = parseInput(input, filename, language, sourceType);
// Give babel transforms an absolute path as relative paths get prefixed
// with `cwd`, which is different across machines
const virtualFilepath = '/' + filename;
Expand Down
Loading
Loading