From 4305d3717506ab3e8f1a3d25d1cebca2efb7a9dc Mon Sep 17 00:00:00 2001 From: Edward Faulkner Date: Tue, 18 Feb 2025 16:52:47 -0500 Subject: [PATCH] Workaround babel evaluation bug Fix #2212 Fix #1812 Supersedes #2215 We were already doing most of the evaluation ourselves. Of all the cases we test, the only spot we were relying on babe's `evaluate` was for the undefined keyword, which was easy to add to our own Evaluator. --- packages/macros/src/babel/evaluate-json.ts | 15 ++++----------- packages/macros/tests/babel/eval.test.ts | 9 +++++++++ 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/packages/macros/src/babel/evaluate-json.ts b/packages/macros/src/babel/evaluate-json.ts index 9dfdc86aa..84a8cc8c7 100644 --- a/packages/macros/src/babel/evaluate-json.ts +++ b/packages/macros/src/babel/evaluate-json.ts @@ -113,12 +113,6 @@ export interface UnknownResult { export type EvaluateResult = ConfidentResult | UnknownResult; -// this is needed to make our strict types work when inter-operating with -// babel's own built-in evaluator -function isConfidentResult(result: { confident: boolean; value: any }): result is ConfidentResult { - return result.confident; -} - export interface EvaluationEnv { knownPaths?: Map; locals?: { [localVar: string]: any }; @@ -193,11 +187,6 @@ export class Evaluator { } private realEvaluate(path: NodePath): EvaluateResult { - let builtIn = path.evaluate(); - if (isConfidentResult(builtIn)) { - return { ...builtIn, hasRuntimeImplementation: false }; - } - if (path.isMemberExpression()) { return this.evaluateMember(path, false); } @@ -224,6 +213,10 @@ export class Evaluator { return { confident: true, value: null, hasRuntimeImplementation: false }; } + if (path.isIdentifier() && path.node.name === 'undefined') { + return { confident: true, value: undefined, hasRuntimeImplementation: false }; + } + if (path.isObjectExpression()) { let props = assertArray(path.get('properties')).map(p => { if (p.isSpreadElement()) { diff --git a/packages/macros/tests/babel/eval.test.ts b/packages/macros/tests/babel/eval.test.ts index 21d35a7ae..9fd6bc7e9 100644 --- a/packages/macros/tests/babel/eval.test.ts +++ b/packages/macros/tests/babel/eval.test.ts @@ -116,6 +116,15 @@ describe('evaluation', function () { expect(code).toMatch(`a: 1`); expect(code).toMatch(`b: unknownValue`); }); + + test('not subject to https://github.com/babel/babel/issues/14197', () => { + let code = transform(` + const state = { a: 1 }; + state.a = 2; + const result = state.a; + `); + expect(code).toMatch('result = state.a'); + }); }, }); });