feat: bun --print (#9358)

* --print cli flag

* less code elimination

* handle cjs module eval results

* make node -p work

* better test

* more tests

* if

* delete commented code

* delete commented code

* EvalGlobalObject

* remove one constructor

---------

Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
This commit is contained in:
Dylan Conway
2024-03-12 18:15:50 -07:00
committed by GitHub
parent 4b0eb47164
commit 3765032dec
20 changed files with 435 additions and 165 deletions

View File

@@ -92,6 +92,9 @@ static bool canPerformFastEnumeration(Structure* s)
return true;
}
extern "C" bool Bun__VM__specifierIsEvalEntryPoint(void*, EncodedJSValue);
extern "C" void Bun__VM__setEntryPointEvalResult(void*, EncodedJSValue);
static bool evaluateCommonJSModuleOnce(JSC::VM& vm, Zig::GlobalObject* globalObject, JSCommonJSModule* moduleObject, JSString* dirname, JSValue filename, WTF::NakedPtr<Exception>& exception)
{
JSSourceCode* code = moduleObject->sourceCode.get();
@@ -119,6 +122,30 @@ static bool evaluateCommonJSModuleOnce(JSC::VM& vm, Zig::GlobalObject* globalObj
moduleObject->hasEvaluated = true;
if (Bun__VM__specifierIsEvalEntryPoint(globalObject->bunVM(), JSValue::encode(filename))) {
// Using same approach as node, `arguments` in the entry point isn't defined
// https://github.com/nodejs/node/blob/592c6907bfe1922f36240e9df076be1864c3d1bd/lib/internal/process/execution.js#L92
globalObject->putDirect(vm, Identifier::fromLatin1(vm, "exports"_s), moduleObject->exportsObject(), 0);
globalObject->putDirect(vm, Identifier::fromLatin1(vm, "require"_s), requireFunction, 0);
globalObject->putDirect(vm, Identifier::fromLatin1(vm, "module"_s), moduleObject, 0);
globalObject->putDirect(vm, Identifier::fromLatin1(vm, "__filename"_s), filename, 0);
globalObject->putDirect(vm, Identifier::fromLatin1(vm, "__dirname"_s), dirname, 0);
JSValue result = JSC::evaluate(globalObject, code->sourceCode(), jsUndefined(), exception);
if (UNLIKELY(exception.get() || result.isEmpty())) {
moduleObject->sourceCode.clear();
return false;
}
Bun__VM__setEntryPointEvalResult(globalObject->bunVM(), JSValue::encode(result));
moduleObject->sourceCode.clear();
return true;
}
// This will return 0 if there was a syntax error or an allocation failure
JSValue fnValue = JSC::evaluate(globalObject, code->sourceCode(), jsUndefined(), exception);