Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
32 changes: 1 addition & 31 deletions src/js/internal/repl/node-shims.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ const path = require("node:path");
const {
ArrayPrototypeJoin,
ArrayPrototypeMap,
ArrayPrototypePush,
ArrayPrototypeSlice,
RegExpPrototypeExec,
RegExpPrototypeSymbolReplace,
Expand Down Expand Up @@ -299,38 +298,9 @@ function stopSigintWatchdog() {
// ---- internalBinding('util') ----------------------------------------------

const ALL_PROPERTIES = 0;
const ONLY_ENUMERABLE = 2;
const SKIP_STRINGS = 8;
const SKIP_SYMBOLS = 16;

function getOwnNonIndexProperties(obj, filter = ALL_PROPERTIES) {
const indexRegex = /^(0|[1-9][0-9]*)$/;
const keys = [];
if (!(filter & SKIP_STRINGS)) {
const names = Object.getOwnPropertyNames(obj);
for (let i = 0; i < names.length; i++) {
const key = names[i];
if (RegExpPrototypeExec(indexRegex, key) !== null) continue;
if (filter & ONLY_ENUMERABLE) {
const desc = Object.getOwnPropertyDescriptor(obj, key);
if (!desc?.enumerable) continue;
}
ArrayPrototypePush(keys, key);
}
}
if (!(filter & SKIP_SYMBOLS)) {
const syms = Object.getOwnPropertySymbols(obj);
for (let i = 0; i < syms.length; i++) {
const sym = syms[i];
if (filter & ONLY_ENUMERABLE) {
const desc = Object.getOwnPropertyDescriptor(obj, sym);
if (!desc?.enumerable) continue;
}
ArrayPrototypePush(keys, sym);
}
}
return keys;
}
const getOwnNonIndexProperties = $newCppFunction("UtilInspect.cpp", "jsFunctionGetOwnNonIndexProperties", 2);

// ---- process.addUncaughtExceptionCaptureCallback polyfill ----------------
// Bun only implements the single-callback set/clear API; emulate Node's
Expand Down
20 changes: 1 addition & 19 deletions src/js/internal/util/inspect.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,7 @@ const NumberPrototypeToString = uncurryThis(Number.prototype.toString);
const NumberPrototypeValueOf = uncurryThis(Number.prototype.valueOf);
const ObjectAssign = Object.assign;
const ObjectDefineProperty = Object.defineProperty;
const ObjectEntries = Object.entries;
const ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
const ObjectGetOwnPropertyDescriptors = Object.getOwnPropertyDescriptors;
const ObjectGetOwnPropertyNames = Object.getOwnPropertyNames;
const ObjectGetOwnPropertySymbols = Object.getOwnPropertySymbols;
const ObjectGetPrototypeOf = Object.getPrototypeOf;
Expand Down Expand Up @@ -2933,23 +2931,7 @@ function stripVTControlCharacters(str) {
}

// utils
function getOwnNonIndexProperties(a, filter = ONLY_ENUMERABLE) {
const desc = ObjectGetOwnPropertyDescriptors(a);
const ret = [];
for (const [k, v] of ObjectEntries(desc)) {
if (!RegExpPrototypeTest(/^(0|[1-9][0-9]*)$/, k) || NumberParseInt(k, 10) >= 2 ** 32 - 1) {
// Arrays are limited in size
if (filter === ONLY_ENUMERABLE && !v.enumerable) continue;
else ArrayPrototypePush.$call(ret, k);
}
}
for (const s of ObjectGetOwnPropertySymbols(a)) {
const v = ObjectGetOwnPropertyDescriptor(a, s);
if (filter === ONLY_ENUMERABLE && !v.enumerable) continue;
ArrayPrototypePush.$call(ret, s);
}
return ret;
}
const getOwnNonIndexProperties = $newCppFunction("UtilInspect.cpp", "jsFunctionGetOwnNonIndexProperties", 2);
Comment thread
robobun marked this conversation as resolved.
Resolved
function getPromiseDetails(promise) {
const state = $peekPromiseStatus(promise);
if (state !== 0) {
Expand Down
53 changes: 53 additions & 0 deletions src/jsc/bindings/UtilInspect.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
#include "JavaScriptCore/JSGlobalObject.h"
#include "ZigGlobalObject.h"
#include "JavaScriptCore/ObjectConstructor.h"
#include "JavaScriptCore/PropertyNameArray.h"
#include "JavaScriptCore/JSArray.h"

namespace Bun {

Expand Down Expand Up @@ -65,4 +67,55 @@ extern "C" JSC::EncodedJSValue JSC__JSValue__callCustomInspectFunction(
RELEASE_AND_RETURN(scope, JSValue::encode(inspectRet));
}

// Port of V8's `internalBinding('util').getOwnNonIndexProperties(object, filter)` used by
// util.inspect and the REPL completer: own keys minus array indices, without materializing
// a name (or descriptor) per element the way Object.getOwnPropertyNames() on an array would.
// `filter` is Node's PropertyFilter bitmask: ONLY_ENUMERABLE = 2, SKIP_STRINGS = 8, SKIP_SYMBOLS = 16.
JSC_DEFINE_HOST_FUNCTION(jsFunctionGetOwnNonIndexProperties, (JSGlobalObject * globalObject, CallFrame* callFrame))
{
auto& vm = JSC::getVM(globalObject);
auto scope = DECLARE_THROW_SCOPE(vm);

JSObject* object = callFrame->argument(0).toObject(globalObject);
RETURN_IF_EXCEPTION(scope, {});
int32_t filter = callFrame->argument(1).toInt32(globalObject);
RETURN_IF_EXCEPTION(scope, {});
constexpr int32_t ONLY_ENUMERABLE = 1 << 1;
constexpr int32_t SKIP_STRINGS = 1 << 3;
constexpr int32_t SKIP_SYMBOLS = 1 << 4;

if ((filter & SKIP_STRINGS) && (filter & SKIP_SYMBOLS))
RELEASE_AND_RETURN(scope, JSValue::encode(constructEmptyArray(globalObject, nullptr)));
PropertyNameMode propertyNameMode = PropertyNameMode::StringsAndSymbols;
if (filter & SKIP_STRINGS)
propertyNameMode = PropertyNameMode::Symbols;
else if (filter & SKIP_SYMBOLS)
propertyNameMode = PropertyNameMode::Strings;
DontEnumPropertiesMode dontEnumMode = (filter & ONLY_ENUMERABLE) ? DontEnumPropertiesMode::Exclude : DontEnumPropertiesMode::Include;

PropertyNameArrayBuilder propertyNames(vm, propertyNameMode, PrivateSymbolMode::Exclude);
// The ordinary [[OwnPropertyKeys]] (Array included) and the typed array one are both "the
// indices, then getOwnNonIndexPropertyNames()", so for those the indices are never produced.
// Anything else that overrides it (Proxy, String objects, arguments, module namespaces, ...)
// has to be asked for all of its keys, and the loop below drops the indices again.
if (isTypedArrayType(object->type()) || !object->structure()->typeInfo().overridesGetOwnPropertyNames())
object->getOwnNonIndexPropertyNames(globalObject, propertyNames, dontEnumMode);
else
object->methodTable()->getOwnPropertyNames(object, globalObject, propertyNames, dontEnumMode);
RETURN_IF_EXCEPTION(scope, {});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

MarkedArgumentBuffer keys;
for (const auto& propertyName : propertyNames) {
if (propertyName.isSymbol())
keys.append(Symbol::create(vm, static_cast<SymbolImpl&>(*propertyName.impl())));
else if (!parseIndex(propertyName))
keys.append(jsOwnedString(vm, propertyName.string()));
}
if (keys.hasOverflowed()) [[unlikely]] {
throwOutOfMemoryError(globalObject, scope);
return {};
}
RELEASE_AND_RETURN(scope, JSValue::encode(constructArray(globalObject, static_cast<ArrayAllocationProfile*>(nullptr), keys)));
Comment thread
robobun marked this conversation as resolved.
Resolved
}

}
5 changes: 5 additions & 0 deletions src/jsc/bindings/UtilInspect.h
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
#pragma once

#include "root.h"

namespace Bun {

JSC::Structure* createUtilInspectOptionsStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject);

// internalBinding('util').getOwnNonIndexProperties(object, filter)
JSC_DECLARE_HOST_FUNCTION(jsFunctionGetOwnNonIndexProperties);

}
124 changes: 124 additions & 0 deletions test/js/node/util/node-inspect-tests/internal-inspect.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import assert from "assert";
import { expect, test } from "bun:test";
import { withoutAggressiveGC } from "harness";
import util from "util";

test("no assertion failures", () => {
Expand Down Expand Up @@ -33,6 +35,128 @@ test("boxed BigInt/Symbol with no prototype are still formatted as boxed primiti
);
});

// Arrays and typed arrays collect their non-index keys through the native
// getOwnNonIndexProperties (UtilInspect.cpp). These pin down what it has to
// report: string and symbol keys in ownKeys order, non-enumerable keys only
// with showHidden, and numeric-looking keys that are not array indices.
test("util.inspect reports the non-index keys of an array", () => {
const array = [1, 2];
array[Symbol("sym")] = "s";
array.str = "v";
Object.defineProperty(array, "hiddenStr", { value: 1, enumerable: false });
Object.defineProperty(array, Symbol("hiddenSym"), { value: 2, enumerable: false });
array["4294967295"] = "not an index";
array["01"] = "not canonical";

expect(util.inspect(array)).toBe(
"[\n" +
" 1,\n" +
" 2,\n" +
" str: 'v',\n" +
" '4294967295': 'not an index',\n" +
" '01': 'not canonical',\n" +
" Symbol(sym): 's'\n" +
"]",
);
expect(util.inspect(array, { showHidden: true })).toBe(
"[\n" +
" 1,\n" +
" 2,\n" +
" [length]: 2,\n" +
" str: 'v',\n" +
" [hiddenStr]: 1,\n" +
" '4294967295': 'not an index',\n" +
" '01': 'not canonical',\n" +
" Symbol(sym): 's',\n" +
" [Symbol(hiddenSym)]: 2\n" +
"]",
);

class Sub extends Array {}
const sub = Sub.from([1]);
sub.extra = 1;
expect(util.inspect(sub)).toBe("Sub(1) [ 1, extra: 1 ]");

const sparse = [];
sparse[3] = 1;
sparse.extra = 1;
expect(util.inspect(sparse, { showHidden: true })).toBe("[ <3 empty items>, 1, [length]: 4, extra: 1 ]");
});

test("util.inspect reports the non-index keys of a typed array", () => {
const u8 = new Uint8Array([1, 2]);
u8[Symbol("sym")] = "s";
u8.str = "v";
Object.defineProperty(u8, "hiddenStr", { value: 1, enumerable: false });
Object.defineProperty(u8, Symbol("hiddenSym"), { value: 2, enumerable: false });

expect(util.inspect(u8)).toBe("Uint8Array(2) [ 1, 2, str: 'v', Symbol(sym): 's' ]");
expect(util.inspect(u8, { showHidden: true })).toBe(
"Uint8Array(2) [\n" +
" 1,\n" +
" 2,\n" +
" [BYTES_PER_ELEMENT]: 1,\n" +
" [length]: 2,\n" +
" [byteLength]: 2,\n" +
" [byteOffset]: 0,\n" +
" [buffer]: ArrayBuffer { [byteLength]: 2 },\n" +
" str: 'v',\n" +
" [hiddenStr]: 1,\n" +
" Symbol(sym): 's',\n" +
" [Symbol(hiddenSym)]: 2\n" +
"]",
);
});

function fastestOf(runs, fn) {
let fastest = Infinity;
for (let i = 0; i < runs; i++) {
const start = performance.now();
fn();
fastest = Math.min(fastest, performance.now() - start);
}
return fastest;
}

test.each([
[
"Array",
length => Object.assign(new Array(length).fill(7), { extra: true }),
length => `[ 7, 7, 7, ... ${length - 3} more items, [length]: ${length}, extra: true ]`,
],
[
"Uint8Array",
length => Object.assign(new Uint8Array(length), { extra: true }),
length =>
`Uint8Array(${length}) [\n` +
" 0,\n" +
" 0,\n" +
" 0,\n" +
` ... ${length - 3} more items,\n` +
" [BYTES_PER_ELEMENT]: 1,\n" +
` [length]: ${length},\n` +
` [byteLength]: ${length},\n` +
" [byteOffset]: 0,\n" +
` [buffer]: ArrayBuffer { [byteLength]: ${length} },\n` +
" extra: true\n" +
"]",
],
])("util.inspect of a large %s does not visit every element", (_, create, expected) => {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const options = { maxArrayLength: 3, showHidden: true };
const small = create(1_000);
const large = create(1_000_000);
expect(util.inspect(small, options)).toBe(expected(1_000));
expect(util.inspect(large, options)).toBe(expected(1_000_000));

withoutAggressiveGC(() => {
const smallMs = fastestOf(5, () => util.inspect(small, options));
const largeMs = fastestOf(5, () => util.inspect(large, options));
// With the keys collected through Object.getOwnPropertyDescriptors() this
// scaled with the length: about 1s for the large one in a release build.
expect(largeMs).toBeLessThan(smallMs * 20 + 50);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
});
});

//! non-standard property, should this be kept?
test.skip("util.stylizeWithHTML", () => {
assert.strictEqual(
Expand Down