Skip to content
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
8478aa6
util.inspect, Console#table: read Map and Set iterators from storage
robobun Sep 11, 2026
204b594
Console#table: do not bound a Map or Set by its size
robobun Sep 12, 2026
2c8f81e
Shorten the comments on previewEntries
robobun Sep 12, 2026
29be5f2
ci: retrigger
robobun Sep 12, 2026
495e5be
test: run the Console#table iterator tests concurrently
robobun Sep 12, 2026
efbaf29
Merge branch 'main' into robobun/c4e079fe/preview-entries-native
robobun Oct 29, 2026
6531d5c
previewEntries: step a private copy of the iterator with the engine's…
robobun Oct 29, 2026
ce44fdd
console.log, Bun.inspect: print a Map or Set iterator without running it
robobun Oct 29, 2026
bd3ca42
console.table, the error printer: read a Map or Set iterator they are…
robobun Oct 29, 2026
2b74f8d
test: a print does not run or use up a Map or Set iterator
robobun Oct 29, 2026
5aee966
Shorten the comments on the native arm
robobun Oct 29, 2026
0f971e7
Merge remote-tracking branch 'origin/main' into robobun/c4e079fe/prev…
robobun Oct 29, 2026
7f3e989
Declare jsFunctionPreviewEntries in the table of built-ins
robobun Oct 29, 2026
a7ff980
Close a Set iterator that is printed on one line with a space
robobun Oct 29, 2026
16482df
Console#table: take isMapIterator and isSetIterator from native code
robobun Oct 29, 2026
6fd8950
test: run the replaced-guard case of Console#table through the shared…
robobun Oct 29, 2026
304b381
previewEntries: reserve for what the iterator has left, not for the c…
robobun Oct 29, 2026
15d410f
Lint: a printer walks a value through formatter::for_each_listed
robobun Oct 29, 2026
ec4b93a
test: more places where native code formats a Map or Set iterator
robobun Oct 29, 2026
0334d09
Lint: tell JSValue::for_each from Iterator::for_each by its arguments
robobun Oct 29, 2026
8548f2c
test: assert the failure text, the entry order and the iterator position
robobun Oct 29, 2026
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
13 changes: 11 additions & 2 deletions src/js/builtins/ConsoleObject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,9 @@ export function write(this: Console, input) {
// TODO: probably could extract `getStringWidth`; probably make that a native function. note how it is copied from `readline.js`
export function createConsoleConstructor(console: typeof globalThis.console) {
const { inspect, formatWithOptions } = require("node:util");
const { isBuffer } = require("node:buffer");
const {
Buffer: { isBuffer },
} = require("node:buffer");
const { isMapIterator, isSetIterator } = require("node:util/types");

const { validateObject, validateInteger, validateArray, validateOneOf } = require("internal/validators");
Expand All @@ -162,6 +164,8 @@ export function createConsoleConstructor(console: typeof globalThis.console) {
const kCounts = Symbol("counts");

const internalGetStringWidth = $newCppFunction("stringWidth.cpp", "jsFunctionBunStringWidth", 1);
// [entries, isKeyValue, length] for a Map or Set iterator, without running or advancing it.
const previewEntries = $newCppFunction("UtilInspect.cpp", "jsFunctionPreviewEntries", 2);

/**
* Returns the number of columns required to display the given string.
Expand Down Expand Up @@ -666,6 +670,11 @@ export function createConsoleConstructor(console: typeof globalThis.console) {
const mapIter = isMapIterator(tabularData);
let isKeyValue = false;
let i = 0;
if (mapIter) {
const res = previewEntries(tabularData);
Comment thread
robobun marked this conversation as resolved.
Resolved
tabularData = res[0];
isKeyValue = res[1];
}

if (isKeyValue || $isMap(tabularData)) {
const keys = [];
Expand All @@ -688,7 +697,7 @@ export function createConsoleConstructor(console: typeof globalThis.console) {
}

const setIter = isSetIterator(tabularData);
// if (setIter) tabularData = previewEntries(tabularData);
if (setIter) tabularData = previewEntries(tabularData)[0];

const setlike = setIter || mapIter || $isSet(tabularData);
if (setlike) {
Expand Down
49 changes: 13 additions & 36 deletions src/js/internal/util/inspect.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,7 @@ const {
TypedArrayPrototypeGetSymbolToStringTag,
} = primordials;

const ArrayFrom = Array.from;
const ArrayPrototypeFilter = uncurryThis(Array.prototype.filter);
const ArrayPrototypeFlat = uncurryThis(Array.prototype.flat);
const ArrayPrototypeForEach = uncurryThis(Array.prototype.forEach);
const ArrayPrototypeIncludes = uncurryThis(Array.prototype.includes);
const ArrayPrototypeIndexOf = uncurryThis(Array.prototype.indexOf);
Expand All @@ -67,8 +65,6 @@ const FunctionPrototypeBind = uncurryThis(Function.prototype.bind);
const FunctionPrototypeToString = uncurryThis(Function.prototype.toString);
const JSONStringify = JSON.stringify;
const MapPrototypeEntries = uncurryThis(Map.prototype.entries);
const MapPrototypeValues = uncurryThis(Map.prototype.values);
const MapPrototypeKeys = uncurryThis(Map.prototype.keys);
const MathFloor = Math.floor;
const MathMax = Math.max;
const MathRound = Math.round;
Expand Down Expand Up @@ -98,7 +94,6 @@ const RegExpPrototypeExec = uncurryThis(RegExp.prototype.exec);
const RegExpPrototypeSymbolReplace = uncurryThis(RegExp.prototype[Symbol.replace]);
const RegExpPrototypeSymbolSplit = uncurryThis(RegExp.prototype[Symbol.split]);
const RegExpPrototypeToString = uncurryThis(RegExp.prototype.toString);
const SetPrototypeEntries = uncurryThis(Set.prototype.entries);
const SetPrototypeValues = uncurryThis(Set.prototype.values);
const StringPrototypeCharCodeAt = uncurryThis(String.prototype.charCodeAt);
const StringPrototypeIncludes = uncurryThis(String.prototype.includes);
Expand Down Expand Up @@ -2256,9 +2251,10 @@ function formatMap(value, ctx, ignored, recurseTimes) {
return output;
}

function formatSetIterInner(ctx, recurseTimes, entries, state) {
// `length` counts every entry there is. `entries` can stop at maxArrayLength of them.
function formatSetIterInner(ctx, recurseTimes, entries, state, length = entries.length) {
const maxArrayLength = MathMax(ctx.maxArrayLength, 0);
const maxLength = $min(maxArrayLength, entries.length);
const maxLength = $min(maxArrayLength, length);
const output = new Array(maxLength);
ctx.indentationLvl += 2;
for (let i = 0; i < maxLength; i++) {
Expand All @@ -2271,17 +2267,16 @@ function formatSetIterInner(ctx, recurseTimes, entries, state) {
// output is not sorted anyway.
ArrayPrototypeSort(output);
}
const remaining = entries.length - maxLength;
const remaining = length - maxLength;
if (remaining > 0) {
ArrayPrototypePush.$call(output, remainingText(remaining));
}
return output;
}

function formatMapIterInner(ctx, recurseTimes, entries, state) {
// Entries exist as [key1, val1, key2, val2, ...]. `len` counts every pair there is.
function formatMapIterInner(ctx, recurseTimes, entries, state, len = entries.length / 2) {
const maxArrayLength = MathMax(ctx.maxArrayLength, 0);
// Entries exist as [key1, val1, key2, val2, ...]
const len = entries.length / 2;
const remaining = len - maxArrayLength;
const maxLength = $min(maxArrayLength, len);
const output = new Array(maxLength);
Expand Down Expand Up @@ -2329,15 +2324,15 @@ function formatWeakMap(ctx, value, recurseTimes) {
}

function formatIterator(braces, ctx, value, recurseTimes) {
const { 0: entries, 1: isKeyValue } = previewEntries(value, true);
const { 0: entries, 1: isKeyValue, 2: length } = previewEntries(value, true, MathMax(ctx.maxArrayLength, 0));
if (isKeyValue) {
// TODO(bun): JSC can also differ between the keys and values iterator, maybe we should also distinguish those in the future?
// Mark entry iterators as such.
braces[0] = RegExpPrototypeSymbolReplace(/ Iterator] {$/, braces[0], " Entries] {");
return formatMapIterInner(ctx, recurseTimes, entries, kMapEntries);
return formatMapIterInner(ctx, recurseTimes, entries, kMapEntries, length);
}

return formatSetIterInner(ctx, recurseTimes, entries, kIterator);
return formatSetIterInner(ctx, recurseTimes, entries, kIterator, length);
}

function formatPromise(ctx, value, recurseTimes) {
Expand Down Expand Up @@ -2783,28 +2778,10 @@ function getProxyDetails(proxy, withHandler = true) {
if (withHandler) return [target, handler];
else return target;
}
function previewEntries(val, isIterator = false) {
if (isIterator) {
// the Map or Set instance this iterator belongs to
const iteratedObject = $getInternalField(val, 1 /*iteratorFieldIteratedObject*/);
// for Maps: 0 = keys, 1 = values, 2 = entries
// for Sets: 1 = keys|values, 2 = entries
const kind = $getInternalField(val, 3 /*iteratorFieldKind*/);
const isEntries = kind === 2;
// TODO(bun): improve performance by not using Array.from and instead using the iterator directly to only get the first
// few entries which will actually be displayed (this requires changing some logic in the call sites of this function)
if ($isMap(iteratedObject)) {
if (isEntries) return [ArrayPrototypeFlat(ArrayFrom(iteratedObject)), true];
else if (kind === 1) return [ArrayFrom(MapPrototypeValues(iteratedObject)), false];
else return [ArrayFrom(MapPrototypeKeys(iteratedObject)), false];
} else if ($isSet(iteratedObject)) {
if (isEntries) return [ArrayPrototypeFlat(ArrayFrom(SetPrototypeEntries(iteratedObject))), true];
else return [ArrayFrom(iteratedObject), false];
}
// TODO(bun): This function is currently only called for Map and Set iterators
// perhaps we should add support for other iterators in the future? (e.g. ArrayIterator and StringIterator)
else throw new Error("previewEntries(): Invalid iterator received");
}
// (iterator, limit) => [flat entries (at most `limit`), isKeyValue, entries left]
const previewIteratorEntries = $newCppFunction("UtilInspect.cpp", "jsFunctionPreviewEntries", 2);
function previewEntries(val, isIterator = false, limit) {
if (isIterator) return previewIteratorEntries(val, limit);
// TODO(bun): are there any JSC APIs for viewing the contents of these in JS?
if (isWeakMap(val)) return [];
if (isWeakSet(val)) return [];
Expand Down
82 changes: 82 additions & 0 deletions src/jsc/bindings/UtilInspect.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
#include "JavaScriptCore/PropertyNameArray.h"
#include "JavaScriptCore/JSArray.h"
#include "JavaScriptCore/IdentifierInlines.h"
#include "JavaScriptCore/JSMapIterator.h"
#include "JavaScriptCore/JSSetIterator.h"

namespace Bun {

Expand Down Expand Up @@ -118,4 +120,84 @@ JSC_DEFINE_HOST_FUNCTION(jsFunctionGetOwnNonIndexProperties, (JSGlobalObject * g
RELEASE_AND_RETURN(scope, JSValue::encode(constructArray(globalObject, static_cast<ArrayAllocationProfile*>(nullptr), keys)));
}

// JSMapIterator::nextWithAdvance in a loop, minus its writes to the iterator. Returns how many entries are left.
template<typename Collection, typename Iterator>
static uint32_t previewRemainingEntries(VM& vm, Iterator* iterator, uint32_t limit, MarkedArgumentBuffer& entries)
{
using Helper = typename Collection::Helper;

JSCell* storageCell = iterator->tryGetStorage();
// An iterator made while the collection had no storage yet picks it up on its first next().
if (!storageCell)
storageCell = iterator->iteratedObject()->storage();
if (!storageCell || storageCell == vm.orderedHashTableSentinel())
return 0;

IterationKind kind = iterator->kind();
auto* storage = uncheckedDowncast<typename Collection::Storage>(storageCell);
typename Helper::Entry entry = iterator->entry();
uint32_t remaining = 0;
while (true) {
// Follows the tables a rehash or a clear() left behind, then skips deleted entries.
auto next = Helper::transitAndNext(vm, *storage, entry);
if (!next.storage)
break;
storage = next.storage;
entry = next.entry + 1;
if (remaining++ >= limit)
continue;
// A Set stores keys only. Its entries() pairs each key with itself.
JSValue value = std::is_same_v<Collection, JSSet> ? next.key : next.value;
if (kind != IterationKind::Values)
entries.append(next.key);
if (kind != IterationKind::Keys)
entries.append(value);
}
return remaining;
}

// internalBinding('util').previewEntries(iterator, true) plus a limit: [flat entries (at most `limit`), isKeyValue, entries left].
JSC_DEFINE_HOST_FUNCTION(jsFunctionPreviewEntries, (JSGlobalObject * globalObject, CallFrame* callFrame))
{
auto& vm = JSC::getVM(globalObject);
auto scope = DECLARE_THROW_SCOPE(vm);

JSValue iteratorValue = callFrame->argument(0);
JSValue limitValue = callFrame->argument(1);
uint32_t limit = std::numeric_limits<uint32_t>::max();
if (limitValue.isNumber()) {
double number = limitValue.asNumber();
// NaN is not > 0.
if (!(number > 0))
limit = 0;
else if (number < limit)
limit = static_cast<uint32_t>(number);
}

MarkedArgumentBuffer entries;
uint32_t length = 0;
bool isKeyValue = false;
if (auto* mapIterator = dynamicDowncast<JSMapIterator>(iteratorValue)) {
isKeyValue = mapIterator->kind() == IterationKind::Entries;
length = previewRemainingEntries<JSMap>(vm, mapIterator, limit, entries);
} else if (auto* setIterator = dynamicDowncast<JSSetIterator>(iteratorValue)) {
isKeyValue = setIterator->kind() == IterationKind::Entries;
length = previewRemainingEntries<JSSet>(vm, setIterator, limit, entries);
} else
return throwVMTypeError(globalObject, scope, "previewEntries() expects a Map or Set iterator"_s);

if (entries.hasOverflowed()) [[unlikely]] {
throwOutOfMemoryError(globalObject, scope);
return {};
}
JSArray* entriesArray = constructArray(globalObject, static_cast<ArrayAllocationProfile*>(nullptr), entries);
RETURN_IF_EXCEPTION(scope, {});

MarkedArgumentBuffer result;
result.append(entriesArray);
result.append(jsBoolean(isKeyValue));
result.append(jsNumber(length));
RELEASE_AND_RETURN(scope, JSValue::encode(constructArray(globalObject, static_cast<ArrayAllocationProfile*>(nullptr), result)));
}

}
3 changes: 3 additions & 0 deletions src/jsc/bindings/UtilInspect.h
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,7 @@ JSC::Structure* createUtilInspectOptionsStructure(JSC::VM& vm, JSC::JSGlobalObje
// internalBinding('util').getOwnNonIndexProperties(object, filter)
JSC_DECLARE_HOST_FUNCTION(jsFunctionGetOwnNonIndexProperties);

// internalBinding('util').previewEntries(iterator, true), with a limit on how many entries it copies out
JSC_DECLARE_HOST_FUNCTION(jsFunctionPreviewEntries);

}
Loading