Commit Graph

36 Commits

Author SHA1 Message Date
Sathya Gunasekaran 58947d9075 [babel] Rename isReactFunction to isReactAPI
Disambiguates better between this and the existing `isReactFunctionLike` 
function.
2023-11-15 09:36:31 +00:00
Mofei Zhang 9965db70bd Revert "[babel] Remove unused PipelineError"
This reverts commit 10d129a8406e9d226abdb6943bf8512e34ce91db 

--- 

Reverts #2311 due to undocumented assumptions being broken. I also added some 
comments to `LoggerEvents` to explain each event type. 

In `Program.ts`, we have something like the following code. `compile` could 
produce any number of errors (not just expected errors / instances of 
`CompilerError`). As an example, we sometimes error in `Codegen` due to babel 
version incompatibilities (`Error: ObjectMethod: Too many arguments passed. 
Received 7 but can receive no more than 5`). 

```js 

try { 

// any error could be thrown here 

compile(input); 

} catch (e) { 

// unknown type for e 

handleError(e, ...); 

} 

```
2023-11-10 17:09:29 -05:00
Sathya Gunasekaran f13594280b [ez] Use BabelFn type 2023-11-09 08:38:00 +00:00
Lauren Tan bb92520ba5 Some existing InvalidConfig errors should be invariants
Now that we have validation of the compiler config, these old errors weren't 
categorized correctly. Readjusted them to be invariants instead.
2023-11-08 14:10:18 -05:00
Sathya Gunasekaran 7aca04a0d6 [babel] Refactor handleError to pass the error first
Pass the most important and required argument as the first parameter.
2023-11-08 16:09:19 +00:00
Sathya Gunasekaran 4e7d437880 [babel] Remove unused PipelineError
Most of the use cases are already handled with ErrorSeverity.InvalidConfig
2023-11-08 16:09:18 +00:00
Sathya Gunasekaran 3f7b9e23e3 Don't allow null to be passed to validateEnvironmentConfig
zod will throw an error if we pass null, so let's not do this. 

Adding a temporary workaround until we start validating PluginOptions.
2023-11-08 16:09:14 +00:00
Sathya Gunasekaran 6405c980eb Use starred-block for multi line comments 2023-11-08 08:27:41 +00:00
Joe Savona 702aadd82b Fix to only add imports if we compiled something
We should only add imports if we actually compiled anything, this is what caused 
the internal issue despite the file in question not having any functions 
opted-in to compilation.
2023-11-07 16:22:03 -08:00
Sathya Gunasekaran 00cb557b12 Add runtime validation for EnvironmentConfig 2023-11-07 11:04:37 +00:00
Sathya Gunasekaran 1c53385db5 Don't plumb PartialEnvironmentConfig
Let's do validation at the API level and pass around the fully parsed config 
inside the plugin.
2023-11-07 11:04:37 +00:00
Sathya Gunasekaran 58a10c0ac1 [babel] Outline insertNewFunctionDeclaration
This lets us use the parsed and validated `gating` and `instrumentForget` 
options.
2023-11-07 11:04:36 +00:00
Sathya Gunasekaran d8734b5136 Remove hasForgetMutatedOriginalSource
Derive it from compiledFns rather than duplicating state
2023-11-07 11:04:35 +00:00
Sathya Gunasekaran bccd06a632 [babel] Simplify noEmit and hasCriticalError check 2023-11-07 11:04:35 +00:00
Sathya Gunasekaran 688305a978 Check if critical error before throwing 2023-11-07 11:04:34 +00:00
Sathya Gunasekaran cf70ef899e Validate options before replacing with compiled function 2023-11-07 11:04:34 +00:00
Sathya Gunasekaran d6ff65ecc7 Add runtime validation for ExternalFunction
Use zod to do runtime validation and throw if incorrect. 

This PR only adds validation for ExternalFunction, will validate other options 
in follow on PRs.
2023-11-07 11:04:33 +00:00
Sathya Gunasekaran 60af6671d7 [ez] Check for use-before-decl only when gating is on 2023-11-02 12:32:40 -07:00
Sathya Gunasekaran 4afee45440 [ez] Add missing ts type 2023-11-02 11:10:33 -07:00
Sathya Gunasekaran adadc21021 [babel] Check if the gated component is used before decl 2023-11-02 11:10:30 -07:00
Lauren Tan 0a7bb7ac7a [babel] Clean up import logic a bit
Addressing feedback from #2218
2023-10-31 12:16:34 -04:00
Lauren Tan ac170f4f0d [babel] Allow userspace useMemoCache
Not every consumer of Forget will be able to run an experimental version of 
React. In the meantime before useMemoCache is stable, provide a way for OSS to 
pass in a userspace impl.
2023-10-31 12:16:31 -04:00
Joe Savona b02f5a5e0e Dont compile code w useMemoCache
Skips compilation of code that has a reference to `useMemoCache()`, as a 
last-resort to avoid double-compilation of code. This is meant as a quick way to 
unblock since we're still seeing some double compilation issues when syncing 
internally.
2023-09-18 09:46:04 -07:00
Joe Savona 14630c0618 Dont compile functions w multiple args (infer mode) 2023-09-14 16:22:06 -07:00
Mofei Zhang f993f0c2a5 [pipeline] panicOnBailout -> panicThreshold; remove isDev logging
--- 

Changed `panicOnBailout: boolean` to `panicThreshold`, which has the following 
options. Note that `ALL_ERRORS` corresponds to `panicOnBailout = true` and 
`CRITICAL_ERRORS` corresponds to `panicOnBailout = false`. `NONE` is a new 
option. 

```js 

export type PanicThresholdOptions = 

// Bail out of compilation on all errors by throwing an exception. 

| "ALL_ERRORS" 

// Bail out of compilation only on critical or unrecognized errors. 

// Instead, silently skip the erroring function. 

| "CRITICAL_ERRORS" 

// Never bail out of compilation. Instead, silently skip the erroring 

// function or file. 

| "NONE"; 

``` 

Jest seems to run babel through a different pipeline than Metro and - 
(perhaps through its complex `require` interjection logic). When running jest 
tests, exceptions thrown by babel transforms will bubble up to the nearest 
exception boundary which is often the jest test itself. This may not be a useful 
signal to anyone running a jest test with Forget enabled, as the erroring code 
may be within Forget itself or a transitively required module. 

Another reason to immediately bailing out on critical errors is that we may want 
to record errors found in the rest of the file. 

--- 

I'm not convinced that this change makes sense. A counterargument is that any 
CriticalErrors *should* be reported as parse errors, regardless of the runtime 
mode. Anyhow, this would be useful long term for our static analysis scripts 
(e.g. collecting info on bailouts and compilation info e.g. # slots used for 
JSX) as we want to compile-as-much-as-possible in those.
2023-09-14 20:00:43 +01:00
Mofei Zhang b2230f62a3 [pipeline] Make logging more structured
--- 

Add types for logged events, including a `CompileSuccess` event which can help 
us record successfully compiled Forget functions and their compilation details 
(e.g. # memoSlots used).
2023-09-14 19:40:39 +01:00
Mofei Zhang 869466bb0b Revamp compilation modes
We currently have multiple flags for targeting which functions to compile, but 
they are actually mutually exclusive. This PR consolidates to a single 
`compilationMode: 'annotation' | 'infer' | 'all'` flag: 

* Annotation compiles only functions that explicitly opt-in with "use forget" 

* Infer compiles explicitly opted-in functions (via "use forget") as well as any 
known/inferred components or hooks: 

* Component declarations 

* Component or hook-like functions (same rules as the ESLint plugin but with an 
extra check for whether it uses JSX or calls a hook) 

* All compiles all top-level functions. We should get rid of this in a follow-up 
and make tests use infer mode by default, and add explicit opt-ins where 
necessary. 

In all modes, "use no forget" always takes precedence and can be used to 
opt-out. The default mode is now "infer".
2023-09-14 19:40:39 +01:00
Mofei Zhang b3730eb496 [ez][be] Make early return explicit in compileAndInsert 2023-09-14 19:40:38 +01:00
Joe Savona 41c23e87c5 Disable compilation of "Components" inside class methods
Minimal repro extracted from our internal codebase. Our inference mode sees that 
this arrow function is component-like and attempts to compile it, which then 
fails because the function accesses `this`  which we bailout on.
2023-08-31 23:16:27 +01:00
Joe Savona 8790324562 Workaround serious Babel bug
I ran into the same issue that @poteto and @gsathya (and probably @mofeiZ) have 
run into: "Duplicate declaration of '$'" caused by Babel visiting a function 
twice despite our calling `skip()`. This PR keeps a set of nodes that we have 
already visited to avoid visiting them again, as a workaround for skip not 
working. 

# Test Plan 

Synced to www and confirmed that the previous bug no longer reproduces, and the 
compiled output looks sane.
2023-08-30 13:21:51 +01:00
Joe Savona 4f55a66d5c Compile args to forwardRef/memo
Completes a todo (ie fixes a silly mistake) from a PR earlier in the stack, so 
we now correctly recognize and compile arguments to `React.forwardRef()` and 
`React.memo()`.
2023-08-29 22:09:42 +01:00
Joe Savona ddc9f8030e Enable compilation of FunctionExpressions
Thanks to the previous diff we can trivially support components or hooks defined 
as a FunctionExpression.
2023-08-29 22:09:41 +01:00
Joe Savona cee08ba750 [rfc] Dont convert ArrowFunction to FunctionDecl
This PR changes the way we compile ArrowFunctionExpression to allow compiling 
more cases, such as within `React.forwardRef()`. We no longer convert arrow 
functions to function declarations. Instead, CodeGenerator emits a generic 
`CodegenFunction` type, and `Program.ts` is responsible for converting that to 
the appropriate type. The rule is basically: 

* Retain the original node type by default. Function declaration in, function 
declaration out. Arrow function in, arrow function out. 

* When gating is enabled, we emit a ConditionalExpression instead of creating a 
temporary variable. If the original (and hence compiled) functions are function 
declarations, we force them into FunctionExpressions only here, since we need an 
expression for each branch of the conditional. Then the rules are: 

* If this is a `export function Foo` ie a named export, replace it with a 
variable declaration with the conditional expression as the initializer, and the 
function name as the variable name. 

* Else, just replace the original function node with the conditional. This works 
for all other cases. 

I'm open to feedback but this seems like a pretty robust approach and will allow 
us to support a lot of real-world cases that we didn't yet, so i think we need 
_something_ in this direction.
2023-08-29 22:09:41 +01:00
Joe Savona 7d11445d8e Revamp compilation modes
We currently have multiple flags for targeting which functions to compile, but 
they are actually mutually exclusive. This PR consolidates to a single 
`compilationMode: 'annotation' | 'infer' | 'all'` flag: 

* Annotation compiles only functions that explicitly opt-in with "use forget" 

* Infer compiles explicitly opted-in functions (via "use forget") as well as any 
known/inferred components or hooks: 

* Component declarations 

* Component or hook-like functions (same rules as the ESLint plugin but with an 
extra check for whether it uses JSX or calls a hook) 

* All compiles all top-level functions. We should get rid of this in a follow-up 
and make tests use infer mode by default, and add explicit opt-ins where 
necessary. 

In all modes, "use no forget" always takes precedence and can be used to 
opt-out. The default mode is now "infer".
2023-08-29 22:09:40 +01:00
Joe Savona 3653ae2de3 Option to infer React functions to compile
Adds a new option to infer which functions to compile, based on React's ESLint 
rule. The main difference is that in addition to checking the function name we 
also check that it creates JSX or calls a hook. This should cover a significant 
majority of components and reduce the chance of accidentally targeting 
non-components, but it will leave some false negatives. 

Note that some cases that the ESLint plugin infers as React functions don't work 
yet: we don't compile FunctionExpressions, only ArrowFunctionExpressions, and 
the way we handle ArrowFunctionExpression doesn't work with things like 
forwardRef or variable declarations. We'll need more updates to fully handle all 
these cases, which I'll do later in the stack.
2023-08-29 22:09:40 +01:00
lauren a0dc166991 [rfc] Remove top level forget directory
Sorry about the thrash in advance! This removes the top level `forget` directory 
which adds unnecessary nesting to our repo 

Hopefully everything still works
2023-08-22 15:04:54 -04:00