Skip to content
Closed
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
6 changes: 3 additions & 3 deletions src/codegen/class-definitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ interface PropertyAttribute {
* from the prototype hash table, instead setting it using `putDirect()`.
*/
privateSymbol?: string;
publicSymbol?: string;
name?: string;
}

Expand Down Expand Up @@ -215,6 +214,7 @@ export class ClassDefinition {
configurable?: boolean;
enumerable?: boolean;
structuredClone?: { transferable: boolean; tag: number; storable: boolean };
/** Installs node's `[nodejs.util.inspect.custom]` method, with `inspect_custom` of the struct as its native half. */
inspectCustom?: boolean;

constructor(options: Partial<ClassDefinition>) {
Expand Down Expand Up @@ -248,11 +248,11 @@ export function define(
proto.inspectCustom = {
fn: "inspectCustom",
length: 2,
publicSymbol: "inspectCustom",
name: "[nodejs.util.inspect.custom]",
passThis: true,
};
}
return new ClassDefinition({
inspectCustom,
...rest,
// `refCounted` is a kind of finalize as far as the C++ wrapper is concerned.
finalize: rest.finalize || rest.refCounted,
Expand Down
63 changes: 48 additions & 15 deletions src/codegen/generate-classes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ function constructorName(typeName) {
return `JS${typeName}Constructor`;
}

/** The proto field that `inspectCustom: true` adds: node's `[nodejs.util.inspect.custom]` method. */
function isInspectCustomHook(obj, name) {
return !!obj.inspectCustom && name === "inspectCustom";
}

function zigExportName(to: Map<string, string>, symbolName: (name: string) => string, prop) {
var { getter, setter, fn } = prop;
const exportNames = {
Expand Down Expand Up @@ -178,7 +183,7 @@ export function generateHashTable(nameToUse, symbolName, typeName, obj, props =

for (const name in props) {
if ("privateSymbol" in props[name] || "internal" in props[name] || "value" in props[name]) continue;
if (name.startsWith("@@")) continue;
if (name.startsWith("@@") || isInspectCustomHook(obj, name)) continue;

rows.push(propRow(symbolName, typeName, name, props[name], wrapped, defaultPropertyAttributes, !!obj.forBind));
}
Expand Down Expand Up @@ -260,19 +265,11 @@ JSC_DECLARE_CUSTOM_GETTER(js${typeName}Constructor);
continue;
}

if (protoFields[name].publicSymbol !== undefined) {
const publicSymbol = protoFields[name].publicSymbol;
const fn = protoFields[name].fn;
if (!fn) throw Error(`(field: ${name}) public field needs 'fn' key `);
const observable_name = protoFields[name].name ?? fn;

if (isInspectCustomHook(obj, name)) {
// A prototype class that derives from this one (the S3 file) inherits the method.
specialSymbols += `
this->putDirect(vm, WebCore::clientData(vm)->builtinNames().${publicSymbol}PublicName(), JSFunction::create(vm, globalObject, ${
protoFields[name].length || 0
}, String("${observable_name}"_s), ${protoSymbolName(
typeName,
fn,
)}Callback, ImplementationVisibility::Public), PropertyAttribute::Function | 0);`;
if (classInfo() == info())
Bun::WebStreams::installInspectCustom(vm, this, ${protoSymbolName(typeName, name)}Callback);`;
continue;
}

Expand Down Expand Up @@ -814,7 +811,24 @@ JSC_DEFINE_CUSTOM_SETTER(${symbolName(typeName, name)}SetterWrap, (JSGlobalObjec
);
}

if ("fn" in proto[name]) {
if (isInspectCustomHook(obj, name)) {
// The receiver can be a Proxy or inherit from an instance. The JS half answers for one that holds none.
rows.push(`
JSC_DEFINE_HOST_FUNCTION(${symbolName(typeName, name)}Callback, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame))
{
auto& vm = JSC::getVM(lexicalGlobalObject);
auto scope = DECLARE_THROW_SCOPE(vm);

${className(typeName)}* thisObject = Bun::WebStreams::inspectInstance<${className(typeName)}>(Bun::WebStreams::inspectHolder(lexicalGlobalObject, callFrame));
if (!thisObject)
RELEASE_AND_RETURN(scope, Bun::WebStreams::inspectFields(lexicalGlobalObject, callFrame, "${typeName}"_s, nullptr, nullptr));

JSC::EnsureStillAliveScope thisArg = JSC::EnsureStillAliveScope(thisObject);
RELEASE_AND_RETURN(scope, ${symbolName(typeName, proto[name].fn)}(thisObject->wrapped(), lexicalGlobalObject, callFrame, JSValue::encode(thisObject)));
}

`);
} else if ("fn" in proto[name]) {
const fn = proto[name].fn;
const invalidThisBehavior = proto[name].invalidThisBehavior ?? InvalidThisBehavior.Throw;
rows.push(`
Expand Down Expand Up @@ -2164,6 +2178,7 @@ const GENERATED_CLASSES_IMPL_HEADER_PRE = `
#include "WebCoreJSBuiltins.h"
#include "ErrorCode+List.h"
#include "ErrorCode.h"
#include "streams/WebStreamsInspectCustom.h"
#include <JavaScriptCore/HeapAnalyzer.h>

#if !OS(WINDOWS)
Expand Down Expand Up @@ -2237,6 +2252,23 @@ const GENERATED_CLASSES_IMPL_FOOTER = `

`;

/** The table behind `Bun::WebStreams::generatedNodeOnlyInspectHooks` (WebStreamsInspectCustom.h). */
function nodeOnlyInspectHooksCppImpl(classes: ClassDefinition[]) {
const hooks = classes
.filter(a => a.inspectCustom)
.map(a => ` WebCore::${protoSymbolName(a.name, "inspectCustom")}Callback,`);
return `
namespace Bun {
namespace WebStreams {
const JSC::NativeFunction generatedNodeOnlyInspectHooks[] = {
${hooks.join("\n")}
};
const size_t generatedNodeOnlyInspectHookCount = ${hooks.length};
} // namespace WebStreams
} // namespace Bun
`;
}

function jsInheritsCppImpl() {
return `
${jsclasses
Expand Down Expand Up @@ -2499,6 +2531,7 @@ function writeCppSerializers() {
allImpls.join("\n"),
writeCppSerializers(classes),
GENERATED_CLASSES_IMPL_FOOTER,
nodeOnlyInspectHooksCppImpl(classes),
jsInheritsCppImpl(),
isTransferableCppImpl(),
]);
Expand Down Expand Up @@ -2551,7 +2584,7 @@ function getPropertySignatureWithComment(
}

// --- Skip internal/private properties ---
if ("internal" in propDef) {
if ("internal" in propDef || isInspectCustomHook(classDef, propName)) {
return null;
}

Expand Down
7 changes: 5 additions & 2 deletions src/js/internal/util/inspect.js
Original file line number Diff line number Diff line change
Expand Up @@ -1509,7 +1509,7 @@ function formatRaw(ctx, value, recurseTimes, typedArray) {
"special",
);
}
throw new AssertionError("handleMaxCallStackSize assertion failed: " + String(err), true);
throw err;
}
const circular = ctx.circular;
if (circular !== undefined) {
Expand Down Expand Up @@ -2403,7 +2403,8 @@ function formatProperty(ctx, value, recurseTimes, key, type, desc, original = va
}
ctx.indentationLvl -= 2;
} catch (err) {
const message = `<Inspection threw (${err.message})>`;
// A nested method can throw null or undefined.
const message = `<Inspection threw (${err == null ? err : err.message})>`;
str = `${s(`[${label}:`, sp)} ${message}${s("]", sp)}`;
}
} else {
Expand Down Expand Up @@ -2827,4 +2828,6 @@ export default {
formatWithOptions,
getStringWidth,
stripVTControlCharacters,
// For internal/util/inspect_hooks. node:util reads the names above only.
getCtxStyle,
};
Loading
Loading