Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[v12.x] backport 27227 #27570

Closed
wants to merge 3 commits into from
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
39 changes: 31 additions & 8 deletions lib/internal/util/inspect.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ const {
kPending,
kRejected,
previewEntries,
getConstructorName: internalGetConstructorName,
propertyFilter: {
ALL_PROPERTIES,
ONLY_ENUMERABLE
Expand All @@ -49,6 +50,8 @@ const {
} = require('internal/errors');

const {
isAsyncFunction,
isGeneratorFunction,
isAnyArrayBuffer,
isArrayBuffer,
isArgumentsObject,
Expand Down Expand Up @@ -347,6 +350,7 @@ function getEmptyFormatArray() {

function getConstructorName(obj, ctx) {
let firstProto;
const tmp = obj;
while (obj) {
const descriptor = Object.getOwnPropertyDescriptor(obj, 'constructor');
if (descriptor !== undefined &&
Expand All @@ -365,7 +369,7 @@ function getConstructorName(obj, ctx) {
return null;
}

return `<${inspect(firstProto, {
return `${internalGetConstructorName(tmp)} <${inspect(firstProto, {
...ctx,
customInspect: false
})}>`;
Expand Down Expand Up @@ -642,14 +646,9 @@ function formatRaw(ctx, value, recurseTimes, typedArray) {
return `${braces[0]}}`;
}
} else if (typeof value === 'function') {
const type = constructor || tag || 'Function';
let name = `${type}`;
if (value.name && typeof value.name === 'string') {
name += `: ${value.name}`;
}
base = getFunctionBase(value, constructor, tag);
if (keys.length === 0)
return ctx.stylize(`[${name}]`, 'special');
base = `[${name}]`;
return ctx.stylize(base, 'special');
} else if (isRegExp(value)) {
// Make RegExps say that they are RegExps
base = RegExpPrototype.toString(
Expand Down Expand Up @@ -834,6 +833,30 @@ function getBoxedBase(value, ctx, keys, constructor, tag) {
return ctx.stylize(base, type.toLowerCase());
}

function getFunctionBase(value, constructor, tag) {
let type = 'Function';
if (isAsyncFunction(value)) {
type = 'AsyncFunction';
} else if (isGeneratorFunction(value)) {
type = 'GeneratorFunction';
}
let base = `[${type}`;
if (constructor === null) {
base += ' (null prototype)';
}
if (value.name !== '') {
base += `: ${value.name}`;
}
base += ']';
if (constructor !== type && constructor !== null) {
base += ` ${constructor}`;
}
if (tag !== '' && constructor !== tag) {
base += ` [${tag}]`;
}
return base;
}

function formatError(err, constructor, tag, ctx) {
// TODO(BridgeAR): Always show the error code if present.
let stack = err.stack || ErrorPrototype.toString(err);
Expand Down
11 changes: 11 additions & 0 deletions src/node_util.cc
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,16 @@ static void GetOwnNonIndexProperties(
args.GetReturnValue().Set(properties);
}

static void GetConstructorName(
const FunctionCallbackInfo<Value>& args) {
CHECK(args[0]->IsObject());

Local<Object> object = args[0].As<Object>();
Local<String> name = object->GetConstructorName();

args.GetReturnValue().Set(name);
}

static void GetPromiseDetails(const FunctionCallbackInfo<Value>& args) {
// Return undefined if it's not a Promise.
if (!args[0]->IsPromise())
Expand Down Expand Up @@ -262,6 +272,7 @@ void Initialize(Local<Object> target,
env->SetMethodNoSideEffect(target, "previewEntries", PreviewEntries);
env->SetMethodNoSideEffect(target, "getOwnNonIndexProperties",
GetOwnNonIndexProperties);
env->SetMethodNoSideEffect(target, "getConstructorName", GetConstructorName);

env->SetMethod(target, "arrayBufferViewHasBuffer", ArrayBufferViewHasBuffer);
Local<Object> constants = Object::New(env->isolate());
Expand Down
70 changes: 59 additions & 11 deletions test/parallel/test-util-inspect.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,51 @@ assert.strictEqual(util.inspect(1), '1');
assert.strictEqual(util.inspect(false), 'false');
assert.strictEqual(util.inspect(''), "''");
assert.strictEqual(util.inspect('hello'), "'hello'");
assert.strictEqual(util.inspect(function() {}), '[Function]');
assert.strictEqual(util.inspect(function abc() {}), '[Function: abc]');
assert.strictEqual(util.inspect(() => {}), '[Function]');
assert.strictEqual(util.inspect(async function() {}), '[AsyncFunction]');
assert.strictEqual(
util.inspect(async function() {}),
'[AsyncFunction]'
);
assert.strictEqual(util.inspect(async () => {}), '[AsyncFunction]');
assert.strictEqual(util.inspect(function*() {}), '[GeneratorFunction]');

// Special function inspection.
{
const fn = (() => function*() {})();
assert.strictEqual(
util.inspect(fn),
'[GeneratorFunction]'
);
Object.setPrototypeOf(fn, Object.getPrototypeOf(async () => {}));
assert.strictEqual(
util.inspect(fn),
'[GeneratorFunction] AsyncFunction'
);
Object.defineProperty(fn, 'name', { value: 5, configurable: true });
assert.strictEqual(
util.inspect(fn),
'[GeneratorFunction: 5] AsyncFunction'
);
Object.defineProperty(fn, Symbol.toStringTag, {
value: 'Foobar',
configurable: true
});
assert.strictEqual(
util.inspect({ ['5']: fn }),
"{ '5': [GeneratorFunction: 5] AsyncFunction [Foobar] }"
);
Object.defineProperty(fn, 'name', { value: '5', configurable: true });
Object.setPrototypeOf(fn, null);
assert.strictEqual(
util.inspect(fn),
'[GeneratorFunction (null prototype): 5] [Foobar]'
);
assert.strictEqual(
util.inspect({ ['5']: fn }),
"{ '5': [GeneratorFunction (null prototype): 5] [Foobar] }"
);
}

assert.strictEqual(util.inspect(undefined), 'undefined');
assert.strictEqual(util.inspect(null), 'null');
assert.strictEqual(util.inspect(/foo(bar\n)?/gi), '/foo(bar\\n)?/gi');
Expand All @@ -59,8 +99,9 @@ assert.strictEqual(util.inspect({}), '{}');
assert.strictEqual(util.inspect({ a: 1 }), '{ a: 1 }');
assert.strictEqual(util.inspect({ a: function() {} }), '{ a: [Function: a] }');
assert.strictEqual(util.inspect({ a: () => {} }), '{ a: [Function: a] }');
assert.strictEqual(util.inspect({ a: async function() {} }),
'{ a: [AsyncFunction: a] }');
// eslint-disable-next-line func-name-matching
assert.strictEqual(util.inspect({ a: async function abc() {} }),
'{ a: [AsyncFunction: abc] }');
assert.strictEqual(util.inspect({ a: async () => {} }),
'{ a: [AsyncFunction: a] }');
assert.strictEqual(util.inspect({ a: function*() {} }),
Expand Down Expand Up @@ -411,7 +452,10 @@ assert.strictEqual(
{
const value = (() => function() {})();
value.aprop = 42;
assert.strictEqual(util.inspect(value), '[Function] { aprop: 42 }');
assert.strictEqual(
util.inspect(value),
'[Function] { aprop: 42 }'
);
}

// Regular expressions with properties.
Expand Down Expand Up @@ -1957,10 +2001,14 @@ assert.strictEqual(
let value = (function() { return function() {}; })();
Object.setPrototypeOf(value, null);
Object.setPrototypeOf(obj, value);
assert.strictEqual(util.inspect(obj), '<[Function]> { a: true }');
assert.strictEqual(
util.inspect(obj),
'Object <[Function (null prototype)]> { a: true }'
);
assert.strictEqual(
util.inspect(obj, { colors: true }),
'<\u001b[36m[Function]\u001b[39m> { a: \u001b[33mtrue\u001b[39m }'
'Object <\u001b[36m[Function (null prototype)]\u001b[39m> ' +
'{ a: \u001b[33mtrue\u001b[39m }'
);

obj = { a: true };
Expand All @@ -1969,14 +2017,14 @@ assert.strictEqual(
Object.setPrototypeOf(obj, value);
assert.strictEqual(
util.inspect(obj),
'<[Array: null prototype] []> { a: true }'
'Object <[Array: null prototype] []> { a: true }'
);

function StorageObject() {}
StorageObject.prototype = Object.create(null);
assert.strictEqual(
util.inspect(new StorageObject()),
'<[Object: null prototype] {}> {}'
'StorageObject <[Object: null prototype] {}> {}'
);

obj = [1, 2, 3];
Expand All @@ -1986,7 +2034,7 @@ assert.strictEqual(
Object.setPrototypeOf(obj, Object.create(null));
assert.strictEqual(
inspect(obj),
"<[Object: null prototype] {}> { '0': 1, '1': 2, '2': 3 }"
"Array <[Object: null prototype] {}> { '0': 1, '1': 2, '2': 3 }"
);
}

Expand Down